forked from PriorityQueue/LeetCodeEveryday
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBinaryTreePaths_NO257.java
66 lines (64 loc) · 2.04 KB
/
BinaryTreePaths_NO257.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
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
private Map<TreeNode, ArrayList<Stack<TreeNode>>> container;
public List<String> binaryTreePaths(TreeNode root) {
if(root ==null)
return new ArrayList<String>();
container = new HashMap<>();
postorder(root);
ArrayList<Stack<TreeNode>> result = container.get(root);
ArrayList<String> realResult = new ArrayList<>();
for (Stack<TreeNode> s:result)
{
StringBuilder sb=new StringBuilder();
sb.append(Integer.toString(s.pop().val));
while(!s.isEmpty())
{
sb.append("->");
TreeNode t=s.pop();
sb.append(Integer.toString(t.val));
}
realResult.add(sb.toString());
}
return realResult;
}
public void postorder(TreeNode t) {
if (t != null) {
postorder(t.left);
postorder(t.right);
if (t.left == null && t.right == null) {
ArrayList<Stack<TreeNode>> arrayList = new ArrayList<>();
Stack<TreeNode> s = new Stack<>();
s.push(t);
arrayList.add(s);
container.put(t, arrayList);
} else {
if (t.left != null) upDate(t,t.left);
if (t.right !=null) upDate(t,t.right);
}
}
}
private void upDate(TreeNode t,TreeNode child) {
ArrayList<Stack<TreeNode>> a = container.get(child);
if (a != null) {
for (Stack<TreeNode> s : a) {
s.push(t);
if (!container.containsKey(t)) {
ArrayList<Stack<TreeNode>> a1 = new ArrayList<>();
a1.add(s);
container.put(t, a1);
} else {
container.get(t).add(s);
}
}
}
}
}