
문제해석
이진트리의 root가 주어졌을 때 트리를 반대로 한 뒤 root를 반환해라
정답 예)
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public TreeNode invertTree(TreeNode root) {
if (root == null) {
return root;
}
if (root.left == null && root.right == null) {
return root;
}
TreeNode temp = root.left;
root.left = root.right;
root.right = temp;
invertTree(root.right);
invertTree(root.left);
return root;
}
}'Algorithm' 카테고리의 다른 글
| [LeetCode 75] 1768. Merge Strings Alternately (0) | 2023.05.18 |
|---|---|
| [leetcode75] 19. Remove Nth Node From End of List (0) | 2023.04.08 |
| [leetcode 75] 43. Multiply Strings (0) | 2023.04.06 |
| [leetcode 75] 202. Happy Number (0) | 2023.04.05 |
| [leetcode 75] 278. First Bad Version (0) | 2023.03.02 |