forked from walnutown/CodingInTheDeep
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinaryTreePreorderTraversal.java
More file actions
71 lines (67 loc) · 2.13 KB
/
Copy pathBinaryTreePreorderTraversal.java
File metadata and controls
71 lines (67 loc) · 2.13 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
/*
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?
*/
// Stack Iterative traversal,
// time: O(n); space: O(h),
// Refer to BinaryTreeInorderTraversal, only position of 'res.add()'' changes
public class Solution{
public ArrayList<Integer> preorderTraversal(TreeNode root) {
ArrayList<Integer> res = new ArrayList<Integer>();
Stack<TreeNode> st = new Stack<TreeNode>();
while (root != null){
st.push(root);
res.add(root.val);
root = root.left;
}
while (!st.isEmpty()){
TreeNode curr = st.pop();
curr = curr.right;
while (curr != null){
st.push(curr);
res.add(curr.val);
curr = curr.left;
}
}
return res;
}
}
// Morris threaded tree pre-order traversal
// Great post from AnnieKim. http://www.cnblogs.com/AnnieKim/archive/2013/06/15/morristraversal.html
// time: O(n); space: O(1)
// Refer to BinaryTreeInorderTraversal, only position of 'res.add()'' changes
public class Solution {
public ArrayList<Integer> preorderTraversal(TreeNode root) {
ArrayList<Integer> res = new ArrayList<Integer>();
if (root == null) return res;
TreeNode curr =root;
while (curr != null){
if (curr.left==null){
res.add(curr.val);
curr = curr.right;
}
else{
// find predecessor
TreeNode prev = curr.left;
while (prev.right!=null && prev.right!=curr) prev = prev.right;
if (prev.right ==null ){ // conenct the predecessor
res.add(curr.val);
prev.right = curr;
curr = curr.left;
}else {
prev.right = null;
curr = curr.right;
}
}
}
return res;
}
}