forked from mengli/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinary Tree Inorder Traversal.java
More file actions
45 lines (42 loc) · 1016 Bytes
/
Binary Tree Inorder Traversal.java
File metadata and controls
45 lines (42 loc) · 1016 Bytes
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
Given a binary tree, return the inorder traversal of its nodes' values.
For example:
Given binary tree {1,#,2,3},
1
\
2
/
3
return [1,3,2].
Note: Recursive solution is trivial, could you do it iteratively?
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public ArrayList<Integer> inorderTraversal(TreeNode root) {
ArrayList<Integer> inOrder = new ArrayList<Integer>();
if (root == null) return inOrder;
Stack<TreeNode> s = new Stack<TreeNode>();
s.add(root);
TreeNode p = root.left;
while (!s.empty()) {
while (p != null) {
s.add(p);
p = p.left;
}
TreeNode n = s.pop();
inOrder.add(n.val);
p = n.right;
if (p != null) {
s.add(p);
p = p.left;
}
}
return inOrder;
}
}