-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPrintTreeZhi
More file actions
61 lines (55 loc) · 1.62 KB
/
Copy pathPrintTreeZhi
File metadata and controls
61 lines (55 loc) · 1.62 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
import java.util.ArrayList;
import java.util.*;
/*
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
*/
public class Solution {
public ArrayList<ArrayList<Integer> > Print(TreeNode pRoot) {
//需要用两个堆栈来实现
ArrayList<ArrayList<Integer>> aList=new ArrayList<ArrayList<Integer>>();
if(pRoot==null)
return aList;
Stack<TreeNode> s1 = new Stack<TreeNode>();
s1.add(pRoot);
Stack<TreeNode> s2 = new Stack<TreeNode>();
while(!s1.isEmpty() || !s2.isEmpty())
{
if(!s1.isEmpty())
{
ArrayList<Integer> aList2=new ArrayList<Integer>();
while(!s1.isEmpty())
{
TreeNode p = s1.pop();
aList2.add(p.val);
if(p.left!=null)
s2.add(p.left);
if(p.right!=null)
s2.add(p.right);
}
aList.add(aList2);
}
else
{
ArrayList<Integer> aList2=new ArrayList<Integer>();
while(!s2.isEmpty())
{
TreeNode p = s2.pop();
aList2.add(p.val);
if(p.right!=null)
s1.add(p.right);
if(p.left!=null)
s1.add(p.left);
}
aList.add(aList2);
}
}
return aList;
}
}