PS/LeetCode
[LeetCode] Invert Binary Tree
판교토끼
2020. 4. 27. 22:18
728x90
https://leetcode.com/problems/invert-binary-tree/
Invert Binary Tree - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
이전 문제에서 List를 뒤집었다면 이번에는 Tree를 뒤집는 문제이다. 재귀를 이용해서 left와 right를 뒤집는 로직이다.
/**
* Definition for a binary tree node.
* public class TreeNode {
* public int val;
* public TreeNode left;
* public TreeNode right;
* public TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public TreeNode InvertTree(TreeNode root) {
if(root==null)
return null;
TreeNode result=new TreeNode(root.val);
if(root.left!=null)
result.right=InvertTree(root.left);
if(root.right!=null)
result.left=InvertTree(root.right);
return result;
}
}
728x90