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

二叉树的遍历(循环方式)

时间:2018-04-07 15:02:24      阅读:172      评论:0      收藏:0      [点我收藏+]

标签:blog   lse   tac   rsa   lis   代码   AC   方式   class   

前序遍历(Preorder Traverse)

根结点-左子树-右子树

Java代码实现:

public List<Integer> preorderTraversal(TreeNode root) {
        List<Integer> ret = new ArrayList<Integer>();
        if(root == null)
            return ret;
        Stack<TreeNode> stack = new Stack<TreeNode>();
        TreeNode cur = root;
        while(cur != null || !stack.isEmpty()){
            if(cur != null){
                ret.add(cur.val);
                stack.push(cur);
                cur = cur.left;
            }else{
                TreeNode node = stack.pop();
                cur = node.right;
            }
        }
        return ret;
    }

 

后序遍历(postorder traverse)

左子树-右子树-根结点

代码实现:

public List<Integer> postorderTraversal(TreeNode root) {
        LinkedList<Integer> ret = new LinkedList<Integer>();
        if(root == null)
            return ret;
        Stack<TreeNode> stack = new Stack<TreeNode>();
        TreeNode cur = root;
        while(cur != null || !stack.isEmpty()){
            if(cur != null){
                stack.push(cur);
                ret.addFirst(cur.val);
                cur = cur.right;
            }else{
                TreeNode node = stack.pop();
                cur = node.left;
            }
        }
        return ret;
    }

 

中序遍历(inorder traverse):

左子树-根结点-右子树

代码实现:

 public List<Integer> inorderTraversal(TreeNode root) {
        List<Integer> ret = new ArrayList<Integer>();
        if(root == null)
            return ret;
        Stack<TreeNode> stack = new Stack<TreeNode>();
        TreeNode cur = root;
        while(!stack.isEmpty() || cur != null){
            if(cur != null){
                stack.push(cur);
                cur = cur.left;
            }else{
                TreeNode node = stack.pop();
                ret.add(node.val);
                cur = node.right;
            }
        }
        return ret;
    }

 

二叉树的遍历(循环方式)

标签:blog   lse   tac   rsa   lis   代码   AC   方式   class   

原文地址:https://www.cnblogs.com/yaoyudadudu/p/8733110.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!