-
Notifications
You must be signed in to change notification settings - Fork 0
/
226. 翻转二叉树.java
80 lines (75 loc) · 2.02 KB
/
226. 翻转二叉树.java
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
/**
* 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;
* }
* }
*/
/**
* 官解答案:https://leetcode-cn.com/problems/invert-binary-tree/solution/fan-zhuan-er-cha-shu-by-leetcode-solution/
* 递归 (自底向上)
*/
class Solution {
public TreeNode invertTree(TreeNode root) {
if (root == null) {
return null;
}
TreeNode left = invertTree(root.left);
TreeNode right = invertTree(root.right);
root.left = right;
root.right = left;
return root;
}
}
/**
* 递归 (自顶向下)
*/
class Solution {
public TreeNode invertTree(TreeNode root) {
if(root == null){
return null;
}
// 将该结点的左右儿子互换,不管是否为null
TreeNode temp = root.left;
root.left = root.right;
root.right = temp;
// 递归左右子树
invertTree(root.left);
invertTree(root.right);
return root;
}
}
/**
* 层序遍历 (迭代)
*/
class Solution {
public TreeNode invertTree(TreeNode root) {
if(root == null){
return null;
}
Queue<TreeNode> nodes = new LinkedList<>();
nodes.offer(root);
while(!nodes.isEmpty()){
TreeNode temp = nodes.poll(); // 出队
if(temp == null){ // 如果某一结点为空,则不考虑
continue;
}
// 将该结点的左右儿子互换,不管是否为null
TreeNode left = temp.left;
temp.left = temp.right;
temp.right = left;
// 不管是否为null,都将其左右儿子入队
nodes.offer(temp.left);
nodes.offer(temp.right);
}
return root;
}
}