
생각 방식
node를 방문할 때마다 child를 서로 바꿔 준다
DFS - recursion
recursion으로 방문 노드마다 해주면 된다
💻 작성 코드
/**
* 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) {
#check if it is an empty tree, and if so, return null
if (root == null) {
return null;
}
#스왑해주기!
TreeNode temp = root.left;
root.left = root.right;
root.right = temp;
#recursive call
invertTree(root.left);
invertTree(root.right);
return root;
}
}
대충 그림으로 표현하자면 이렇게 된다


Runtiime은 왜 저렇게 나오는지 모르겠지만....
'코딩 테스트 > leetcode' 카테고리의 다른 글
| 543. Diameter of Binary Tree (Easy) [JavaScript] (1) | 2024.02.13 |
|---|---|
| 104. Maximum Depth of Binary Tree (Easy) [Java] (1) | 2024.02.09 |
| 55. Jump Game (Medium) [Python] (0) | 2024.02.04 |
| 53. Maximum Subarray (Medium) [Python] (0) | 2024.02.04 |
| 746. Min Cost Climbing Stairs (Easy) [Python] (0) | 2024.02.04 |