leetcode.com/problems/invert-binary-tree/
Invert a binary tree.
Input:
4
/ \
2 7
/ \ / \
1 3 6 9
Output:
4
/ \
7 2
/ \ / \
9 6 3 1
재귀를 이용해서 왼쪽과 오른쪽을 바꾸고 할당한다.
class Solution {
public TreeNode invertTree(TreeNode root) {
if(root == null){
return null;
}
TreeNode right = invertTree(root.right);
TreeNode left = invertTree(root.left);
root.left = right;
root.right = left;
return root;
}
}
'개발자 > algorithm' 카테고리의 다른 글
LeetCode, Single Number (Java) (0) | 2021.01.05 |
---|---|
LeetCode, Move Zeroes (Java) (0) | 2021.01.05 |
LeetCode, Maximum Depth of Binary Tree (Java) (0) | 2021.01.03 |
LeetCode, Merge Two Binary Trees (Java) (0) | 2021.01.03 |
LeetCode, Custom Sort String (Java) (0) | 2020.12.30 |