LeetCode | 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?

 

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
 //中序遍历:left->root->right
public class Solution {                   //思想上一题先序遍历一模一样
    
    public ArrayList<Integer> inorderTraversal(ArrayList<Integer> list,TreeNode root){
        if(root==null) return list;
        if(root.left!=null) inorderTraversal(list,root.left);
        list.add(root.val);
        if(root.right!=null) inorderTraversal(list,root.right);
        return list;
    }
    
    public List<Integer> inorderTraversal(TreeNode root) {
        ArrayList<Integer> result = new ArrayList<Integer>();
        if(root==null) return result;
        
        if(root.left!=null) inorderTraversal(result,root.left);
        result.add(root.val);
        if(root.right!=null) inorderTraversal(result,root.right);
        
        return result;
    }
}

 


//迭代写法,要点:
 //1.需要记录一个node是第几次被从stack中pop 
 //2.第一次pop出一个node后,按照right child, node, left child的顺序将这三个node(如果存在)放回stack
public class Solution {                   
    public List<Integer> inorderTraversal(TreeNode root) {
        ArrayList<Integer> result = new ArrayList<Integer>();
        if(root==null) return result;
        
        Stack<TreeNode> nodeStack = new Stack<TreeNode>();
        Stack<Integer> countStack = new Stack<Integer>();   //对应node的标记栈,记录每个node是第几次被pop出stack,初始为0
        nodeStack.push(root);                               //此时root已经不为空
        countStack.push(0);
        
        while(!nodeStack.empty()){
            TreeNode node = nodeStack.pop();
            int count = countStack.pop();
            if(count==1){                        //只有第二次被pop出stack的node,才遍历到result中
                result.add(node.val);
            }else{                               //否则就按右->根(改写标记位)->左的顺序依次压入栈
                if(node.right!=null){            
                    nodeStack.push(node.right);
                    countStack.push(0);
                }
                nodeStack.push(node);            //重新把node压回栈,并改写标志位
                countStack.push(1);
                if(node.left!=null){             //考虑栈的后入先出,则下次循环时,先弹出left来判断
                    nodeStack.push(node.left);   //则正好符合中序遍历的要求left->root->right
                    countStack.push(0);
                }
            }
        }
        
        return result;
    }
}






 

posted @ 2014-11-14 15:22  Mr.do  阅读(100)  评论(0编辑  收藏  举报