LeetCode之二叉树中序迭代遍历

问题描述:

/**
 * 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?
 */

题目说,递归解法很easy。要让用迭代的方法进行遍历。
对于二叉树的操作,不用递归的话,要想遍历肯定要用到栈来操作。
具体代码如下:

public static ArrayList inorderTraversal(TreeNode root){
        ArrayList inOrder = new ArrayList();
        if(root==null)
            return inOrder;
        Stacks=new Stack();
        s.add(root);
        TreeNode p=root.left;
        while(!s.empty()){
            while(p!=null)
            {
                s.add(p);
                p=p.left;
            }
            TreeNode n = s.pop();
            inOrder.add(n.val);
            p=n.right;
            if(p!=null)
            {
                s.add(p);
                p=p.left;
            }
        }
        return inOrder;

    }
    //测试代码:
    public static void main(String arg[])
    {
        TreeNode r1 = new TreeNode(1);  
        TreeNode r2 = new TreeNode(2);  
        TreeNode r3 = new TreeNode(3);  

        r1.right = r2;  
        r2.left = r3;  

        ArrayList array=inorderTraversal(r1);
        for(int i=0;iout.print(array.get(i)+",");
        }

    }

你可能感兴趣的:(LeetCode,leetcode,二叉树,迭代)