public ArrayList < Integer > inorderTraversal(TreeNode root) {
List<Integer> ans =new ArrayList<> ();
if (root ==null) {
return list;
}
Stack<TreeNode> stack =new Stack <>();
TreeNode curr = root;
while (!stack.isEmpty() || curr !=null) {
if (curr !=null) {
stack.push(curr);
curr = curr.left;
} else {
TreeNode t = stack.pop();
ans.add(t.val);
curr = t.right;
}
}
return ans;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public List<Integer>inorderTraversal(TreeNode root) {
List<Integer> ans =new LinkedList<Integer>();
if (root ==null) {
return ans;
}
Stack<TreeNode> stack =new Stack<TreeNode>();
TreeNode cur = root;
while (cur !=null||!stack.isEmpty()) {
while (cur !=null) {// Travel to each node's left child, till reach the left leaf stack.push(cur);
cur = cur.left;
}
cur = stack.pop(); // Backtrack to higher level node A ans.add(cur.val); // Add the node to the result list cur = cur.right; // Switch to A'right branch }
return ans;
}