首页 > 其他 > 详细

二叉树的遍历(非递归)

时间:2015-05-05 18:49:59      阅读:122      评论:0      收藏:0      [点我收藏+]

1. 先序遍历

public void preorder(TreeNode root) {
        if(root == null) return;
        Stack<TreeNode> stack = new Stack<TreeNode>();
        while(true) {
            if(root == null) {
                if(stack.isEmpty())
                    break;
                root = stack.pop();
            } else {
                System.out.println(root.val);
                if(root.right != null)
                    stack.push(root.right);
                root = root.left;
            }
        }
    }

 

2. 中序遍历

public void inorder(TreeNode root) {
        if(root == null) return;
        Stack<TreeNode> stack = new Stack<TreeNode>();
        while(true) {
            if(root == null) {
                if(stack.isEmpty()) 
                    break;
                root = stack.pop();
                System.out.println(root.val);
                root = root.right;
            } else if(root.left != null) {
                stack.push(root);
                root = root.left;
            } else {
                System.out.println(root.val);
                root = root.right;
            }
        }
    }

 

3. 后序遍历, 需要两个栈,其中一个栈用来记录对应节点是否已经访问了它的右节点

public void postorder(TreeNode root) {
        if(root == null) return;
        Stack<TreeNode> stack = new Stack<TreeNode>();
        Stack<Boolean> flags = new Stack<Boolean>();
        while(true) {
            if(root == null) {
                if(stack.isEmpty()) { 
                    break;
                } if(flags.peek()) {
                    System.out.println(stack.pop().val);
                    flags.pop();
                } else {
                    flags.pop();
                    flags.push(true);
                    root = stack.peek().right;
                }
            } else if(root.left != null) {
                stack.push(root);
                flags.push(false);
                root = root.left;
            } else if(root.right != null) {
                stack.push(root);
                flags.push(true);
                root = root.right;
            } else {
                System.out.println(root.val);
                root = null;
            }
        }
    }

 

二叉树的遍历(非递归)

原文:http://www.cnblogs.com/linxiong/p/4479812.html

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