Binary Tree Inorder Traversal
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?
confused what "{1,#,2,3}"
means? > read more on how binary tree is serialized on OJ.
/** * Definition for binary tree * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { public ArrayList<Integer> inorderTraversal(TreeNode root) { if (root==null){ return new ArrayList<Integer>(); } ArrayList<Integer> ret = new ArrayList<Integer>(); Stack<TreeNode> stack = new Stack<TreeNode>(); stack.push(root); while (!stack.empty()) { TreeNode p = null; //找到最左子树的叶子 while (stack.peek() != null){ p = stack.peek(); stack.push(p.left); p = p.left; } //把最后叶子节点left的null弹出 stack.pop(); //如果是最右子树的叶子节点的时候栈就空了 if (stack.empty()){ return ret; } p = stack.pop(); ret.add(p.val); //把右子树当做根节点,找最左 stack.push(p.right); } return ret; } }