码迷,mamicode.com
首页 > 其他好文 > 详细

二叉树的遍历(非递归)

时间:2015-05-05 18:51:09      阅读:108      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!