forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathforest000014.java
More file actions
42 lines (38 loc) ยท 1.1 KB
/
forest000014.java
File metadata and controls
42 lines (38 loc) ยท 1.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
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;
return root;
}
}