-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathBinaryTreeInorderTraversal.java
More file actions
60 lines (59 loc) · 1.66 KB
/
BinaryTreeInorderTraversal.java
File metadata and controls
60 lines (59 loc) · 1.66 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
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
// Modified the tree
public class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
if (root == null) {
return new ArrayList<>();
}
Stack<TreeNode> st = new Stack<>();
st.push(root);
List<Integer> res = new ArrayList<>();
while (!st.isEmpty()) {
TreeNode node = st.pop();
if (node.left == null && node.right == null) {
res.add(node.val);
} else {
if (node.right != null) {
st.push(node.right);
}
st.push(node);
if (node.left != null) {
st.push(node.left);
}
node.left = null;
node.right = null;
}
}
return res;
}
}
// Without changing the tree
public class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
if (root == null) {
return new ArrayList<Integer>();
}
Stack<TreeNode> st = new Stack<>();
List<Integer> result = new ArrayList<>();
TreeNode cur = root;
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;
}
}