首页 > 其他 > 详细

二叉树遍历的非递归

时间:2016-03-01 13:02:01      阅读:138      评论:0      收藏:0      [点我收藏+]

前序遍历的非递归:1、在入栈时加入结果集,不停的取左子树入栈,直到为空。2、如果栈非空,pop栈顶结点,取其右子树作为当前结点,继续第一步,直到栈为空

中序遍历的非递归:1、在入栈时,不停的取左子树入栈,直到为空。2、如果栈非空,pop栈顶结点,加入结点集,取其右子树作为当前结点,继续第一步,直到栈为空

后序遍历的非递归:1、在遍历结点时,总是先将右子树结点入栈,再将左子树结点入栈。2、如果左子树结点和右子树结点为空或者右子树结点已经访问过,弹出栈顶元素,标记已访问结点,加入结果集,直到栈为空。

具体代码如下:

class TreeNode
{
    int val;
    TreeNode left;
    TreeNode right;
    TreeNode(int x) { val = x; }
}

class Solution
{
    public List<Integer> preorderTraversal(TreeNode root)
    {
        List<Integer> ret = new ArrayList<Integer>();

        Stack<TreeNode> stack = new Stack<TreeNode>();
        TreeNode cur = root;

        while(cur != null || !stack.empty())
        {
            while (cur != null)
            {
                ret.add(cur.val);
                stack.push(cur);
                cur = cur.left;
            }

            if (!stack.empty())
            {
                TreeNode tmp = stack.pop();
                cur = tmp.right;
            }
        }

        return ret;
    }


    public List<Integer> inorderTraversal(TreeNode root)
    {
        List<Integer> ret = new ArrayList<Integer>();

        Stack<TreeNode> stack = new Stack<TreeNode>();
        TreeNode cur = root;

        while(cur != null || !stack.empty())
        {
            while (cur != null)
            {
                stack.push(cur);
                cur = cur.left;
            }

            if (!stack.empty())
            {
                TreeNode tmp = stack.pop();
                ret.add(tmp.val);
                cur = tmp.right;
            }
        }

        return ret;
    }

    public List<Integer> postorderTraversal(TreeNode root)
    {
        List<Integer> ret = new ArrayList<Integer>();

        Stack<TreeNode> stack = new Stack<TreeNode>();
        TreeNode cur = root, pre = null;

        if (null == cur) return null;

        stack.push(cur);
        while (!stack.empty())
        {
            TreeNode tmp = stack.peek();

            if ((tmp.left == null && tmp.right == null) || (pre != null && tmp.right == pre))
            {
                ret.add(tmp.val);
                stack.pop();
                pre = tmp;
            }
            else
            {
                if (tmp.right != null) stack.push(tmp.right);
                if (tmp.left != null) stack.push(tmp.left);
            }
        }

        return ret;
    }
}


二叉树遍历的非递归

原文:http://blog.csdn.net/xiexingshishu/article/details/50771392

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!