forked from chuyi2007/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinaryTreeInorderTraversal.java
More file actions
71 lines (69 loc) · 2.11 KB
/
BinaryTreeInorderTraversal.java
File metadata and controls
71 lines (69 loc) · 2.11 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
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
//recursion, O(N)
public class Solution {
public ArrayList<Integer> inorderTraversal(TreeNode root) {
// Start typing your Java solution below
// DO NOT write main() function
ArrayList<Integer> result = new ArrayList<Integer>();
if(node == null)
return new ArrayList<Integer>();
result.addAll(inorderTraversal(node.left));
result.add(node.val);
result.addAll(inorderTraversal(node.right));
return result;
}
}
//iteration 1, O(N)
public class Solution{
public ArrayList<Integer> inorderTraversal(TreeNode root) {
// Start typing your Java solution below
// DO NOT write main() function
Stack<TreeNode> st = new Stack<TreeNode>();
TreeNode cur = root;
ArrayList<Integer> result = new ArrayList<Integer>();
while(!st.isEmpty() || cur != null){
if(cur != null){
st.push(cur);
cur = cur.left;
}
else{
cur = st.pop();
result.add(cur.val);
cur = cur.right;
}
}
return result;
}
}
//iteration 2, O(N)
public class Solution {
public ArrayList<Integer> inorderTraversal(TreeNode root) {
// Start typing your Java solution below
// DO NOT write main() function
Stack<TreeNode> st = new Stack<TreeNode>();
st.push(root);
ArrayList<Integer> result = new ArrayList<Integer>();
while(!st.isEmpty() && st.peek() != null){
TreeNode node = st.pop();
if(node.right != null)
st.push(node.right);
if(node.left != null){
st.push(node);
st.push(node.left);
}
else
result.add(node.val);
node.left = null;
node.right = null;
}
return result;
}
}