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?
代码如下:
class TreeNode
{
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}
class Solution
{
public List<Integer> inorderTraversal(TreeNode root)
{
Stack<TreeNode> stack = new Stack<TreeNode>();
TreeNode current = root;
List<Integer> ret = new ArrayList<Integer>();
while (current != null || !stack.empty())
{
while (current != null)
{
stack.push(current);
current = current.left;
}
if (!stack.empty())
{
TreeNode tmp = stack.pop();
ret.add(tmp.val);
current = tmp.right;
}
}
return ret;
}
}