-
Notifications
You must be signed in to change notification settings - Fork 3
/
lc144.java
44 lines (44 loc) · 1001 Bytes
/
lc144.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
// Given a binary tree, return the preorder traversal of its nodes' values.
//
// For example:
// Given binary tree {1,#,2,3},
// 1
// \
// 2
// /
// 3
// return [1,2,3].
//
// Note: Recursive solution is trivial, could you do it iteratively?
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> res = new ArrayList<Integer>();
Stack<TreeNode> stack = new Stack<TreeNode>();
while(root != null)
{
stack.push(root);
res.add(root.val);
root = root.left;
}
while(!stack.isEmpty()){
TreeNode cur = stack.pop();
cur = cur.right;
while(cur != null)
{
stack.push(cur);
res.add(cur.val);
cur = cur.left;
}
}
return res;
}
}