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 List<Integer> inorderTraversal(TreeNode root) {
List<Integer> result = new ArrayList<Integer>();
if(root==null) return result;
Stack<TreeNode> st = new Stack<TreeNode>();
TreeNode p = root;
while(p != null || st.size()>0){
while(p != null){
st.push(p);
p = p.left;
}
if(st.size()>0){
TreeNode temp = st.pop();
result.add(temp.val);
p = temp.right;
}
}
return result;
}
}