Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 42 additions & 0 deletions invert-binary-tree/forest000014.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
/*
# Time Complexity: O(n)
- 전체 노드를 1번씩 탐색
# Space Complexity: O(n)
- 재귀 호출의 각 depth마다 temp 노드 하나씩 생성
# Solution
- 현재 노드의 왼쪽 자식과 오른쪽 자식을 각각 재귀 호출하여 자식의 자식 노드들을 반전시킨뒤,
- 왼쪽 자식과 오른쪽 자식을 반전시킵니다.
- base condition으로, 현재 노드가 null인 경우 null을 early return 합니다.
*/

/**
* 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 null;
}

invertTree(root.left);
invertTree(root.right);

TreeNode temp = root.left;
root.left = root.right;
root.right = temp;
Comment on lines +33 to +38
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

요 부분은 저도 피드백 받았는데 TreeNode의 생성자가 오버로딩 되있기에 이를 활용하면 내부 로직을 엄청 간소화할 수 있더라구요(메모리도 아낄 수 있고). 한번 검토해보시는걸 추천합니다!


return root;
}
}