-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathMain47.java
More file actions
53 lines (50 loc) · 1.56 KB
/
Main47.java
File metadata and controls
53 lines (50 loc) · 1.56 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
43
44
45
46
47
48
49
50
51
52
53
package JZOfferTuJi;
import java.util.Deque;
import java.util.LinkedList;
public class Main47 {
public TreeNode pruneTree(TreeNode root) {
Deque<TreeNode> stack = new LinkedList<>();
Deque<TreeNode> mark = new LinkedList<>(); // 使用辅助栈
TreeNode node = root;
while (node != null || !stack.isEmpty()){
while (node != null){
stack.push(node);
node = node.left;
}
while (!mark.isEmpty() && mark.peek() == stack.peek()){
TreeNode cur = stack.pop();
if(mark.pop().val == 0 && cur.left == null && cur.right == null){
if(!stack.isEmpty()){
TreeNode tmp = stack.peek();
if(tmp.left == cur){
tmp.left = null;
}else{
tmp.right = null;
}
} else{
return null;
}
}
}
if(!stack.isEmpty()){
node = stack.peek();
mark.push(node);
node = node.right;
}
}
return root;
}
}
class Main47_1{
public TreeNode pruneTree(TreeNode root) {
if(root == null) {
return null;
}
root.left = pruneTree(root.left);
root.right = pruneTree(root.right);
if (root.val == 0 && root.left == null && root.right == null){
root = null;
}
return root;
}
}