-
Notifications
You must be signed in to change notification settings - Fork 0
/
144i.java
36 lines (35 loc) · 1.08 KB
/
144i.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
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
//create list of integer to save sequence
List<Integer> preseq = new ArrayList<Integer>();
//stack for iteration
Stack<TreeNode> backups = new Stack<TreeNode>();
while(root!=null){
//visit root first
preseq.add(root.val);
//lookup left & save the backup node(left node)
if(root.left!=null){
if(root.right!=null)
backups.push(root.right);
root = root.left;
}
//no left, then go for right node
else if(root.right!=null)
root = root.right;
//no left or right, go for backups.
else if(!backups.empty())
root = backups.pop();
else break;
}
return preseq;
}
}