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]
.
Use a stack data structure, if the left node is not null, add it to stack, otherwise pop a node from stack, print it out and search it's right sub tree.
public class Solution {
public ArrayList<Integer> inorderTraversal(TreeNode root) {
ArrayList<Integer> list = new ArrayList<Integer>();
if(root == null) return list;
Stack<TreeNode> stack = new Stack<TreeNode>();
TreeNode node = root;
stack.add(node);
while(!stack.empty()){
if(node != null && node.left != null){
node = node.left;
stack.add(node);
}else{
node = stack.pop();
list.add(node.val);
if(node.right != null){
node = node.right;
stack.add(node);
}else{
node = null;
}
}
}
return list;
}
}