Using stack to store all the elements on the left
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> list = new ArrayList<Integer>();
if (root == null) return list;
Stack<TreeNode> stack = new Stack<TreeNode>();
TreeNode p = root;
while (!stack.empty() || p != null) {
if (p!=null) {
stack.push(p);
p = p.left;
} else {
TreeNode temp = stack.pop();
list.add(temp.val);
p = temp.right;
}
}
return list;
}
No comments:
Post a Comment