Skip to content

Commit f443272

Browse files
committed
二叉树反转简化
1 parent 1605c5c commit f443272

File tree

1 file changed

+7
-72
lines changed

1 file changed

+7
-72
lines changed

MD/算法-二叉树-二叉树反转.md

Lines changed: 7 additions & 72 deletions
Original file line numberDiff line numberDiff line change
@@ -16,82 +16,17 @@
1616
```
1717

1818
```java
19-
import java.util.LinkedList;
20-
21-
class TreeNode {
22-
public TreeNode left;
23-
public TreeNode right;
24-
public int value;
25-
26-
public TreeNode(int value) {
27-
this.value = value;
28-
}
29-
30-
public TreeNode invertNode(TreeNode root) {
31-
if (root == null) {
19+
class Solution {
20+
public TreeNode invertTree(TreeNode root) {
21+
if(root == null){
3222
return null;
3323
}
24+
invertTree(root.left);
25+
invertTree(root.right);
3426
TreeNode temp = root.left;
35-
root.left = invertNode(root.right);
36-
root.right = invertNode(temp);
27+
root.left = root.right;
28+
root.right = temp;
3729
return root;
3830
}
39-
// 另一种写法
40-
// public TreeNode invertNode(TreeNode root) {
41-
// if (root == null) {
42-
// return null;
43-
// }
44-
// TreeNode temp = root.left;
45-
// root.left = root.right;
46-
// root.right = temp;
47-
// invertNode(root.left);
48-
// invertNode(root.right);
49-
// return root;
50-
// }
51-
52-
// 该方法是按二叉树每层从左往右的顺序打印结点,不属于本题考察的范围,但也属于面试题目中会考察的问题
53-
public void printTreeNode() {
54-
LinkedList<TreeNode> queue = new LinkedList<>();
55-
queue.add(this);
56-
57-
TreeNode currentLineRightestNode = new TreeNode(this.value); // 直接使用this会将root的value改变,所以需要clone一个相同值的对象
58-
TreeNode nextLineRightestNode = null;
59-
60-
while (!queue.isEmpty()) {
61-
TreeNode currentNode = queue.poll();
62-
63-
if (currentNode.left != null) {
64-
queue.add(currentNode.left);
65-
nextLineRightestNode = currentNode.left;
66-
}
67-
if (currentNode.right != null) {
68-
queue.add(currentNode.right);
69-
nextLineRightestNode = currentNode.right;
70-
}
71-
72-
System.out.print(currentNode.value);
73-
74-
if (currentNode.value == currentLineRightestNode.value) {
75-
System.out.println();
76-
currentLineRightestNode.value = nextLineRightestNode.value;
77-
}
78-
}
79-
}
80-
}
81-
82-
public class ReverseBinaryTree {
83-
public static void main(String[] args) {
84-
TreeNode root = new TreeNode(4);
85-
root.left = new TreeNode(2);
86-
root.right = new TreeNode(7);
87-
root.left.left = new TreeNode(1);
88-
root.left.right = new TreeNode(3);
89-
root.right.left = new TreeNode(6);
90-
root.right.right = new TreeNode(9);
91-
root.printTreeNode();
92-
System.out.println("-------");
93-
root.invertNode(root);
94-
root.printTreeNode();
95-
}
9631
}
9732
```

0 commit comments

Comments
 (0)