-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTragetTreePath25.java
More file actions
99 lines (90 loc) · 3.21 KB
/
TragetTreePath25.java
File metadata and controls
99 lines (90 loc) · 3.21 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
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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
package offer;
import java.util.*;
public class TragetTreePath25 {
public ArrayList<ArrayList<Integer>> FindPath(TreeNode23 root,
int target) {
ArrayList<ArrayList<Integer>> pathlist = new ArrayList<ArrayList<Integer>>();
Stack<TreeNode23> s = new Stack<TreeNode23>();
if(root == null){
return pathlist;
}
int sum = 0;
findPathC(root, target, sum, pathlist, s);
return pathlist;
}
private void findPathC(TreeNode23 node, int target, int sum,
ArrayList<ArrayList<Integer>> path,Stack<TreeNode23> s){
if(node == null) return ;
s.push(node);
sum += node.data;
//叶子节点
if(node.left == null && node.right == null){
if(sum == target){
ArrayList<Integer> arr = new ArrayList<Integer>();
for (TreeNode23 treeNode : s) {
arr.add(treeNode.data);
}
path.add(arr);
}
}
if(node.left != null){
findPathC(node.left, target, sum, path, s);
}
if(node.right != null){
findPathC(node.right, target, sum, path, s);
}
s.pop();
}
public ArrayList<ArrayList<Integer>> FindPath2(TreeNode23 root, int target){
Stack<TreeNode23> s = new Stack<TreeNode23>();
ArrayList<ArrayList<Integer>> path = new ArrayList<ArrayList<Integer>>();
int sum = 0;
TreeNode23 last = null; //
while(root != null){
while(root != null){
sum += root.data;
s.push(root);
last = root;
// root.isVistied = true;
if(root.left == null && root.right == null){
if(sum == target){
ArrayList<Integer> arr = new ArrayList<Integer>();
for (TreeNode23 nodet : s) {
arr.add(nodet.data);
}
path.add(arr);
}
//Ҷ�ӽڵ���ȥ��
sum -= s.pop().data;
}
root = root.left;
}
if(!s.isEmpty()){
TreeNode23 top = s.peek();
// if(!top.right.isVistied){
if(top.right != last){
root = top.right;
}else{
sum -= s.pop().data;
if(sum == 0){
break;
}
root = s.peek().right;
}
}
}
return path;
}
public static void main(String[] args) {
TreeOperate23 op = new TreeOperate23();
int[] a = { 10, 5, 12, 4, 7, -1, -1, -1, 2};
// int [] a = {5,4,-1,3,-1,-1,-1,-1,-1,-1,-1};
TreeNode23 root = null;
//������
root = op.createSquence(a,0);
ArrayList<ArrayList<Integer>> ll1 = new TragetTreePath25().FindPath(root,22);
System.out.println(ll1);
ArrayList<ArrayList<Integer>> ll = new TragetTreePath25().FindPath2(root, 22);
System.out.println(ll);
}
}