Binary Tree Traversal - two styles of solutions

本文介绍了二叉树遍历中的两种迭代解决方案,并详细对比了先序遍历的两种不同实现方式。一种是在遍历的同时将根节点压入栈中,另一种则是先将子节点压入栈中再进行遍历。通过对这两种方法的分析,最终推荐使用第一种方法以简化中序遍历的实现。

经过查询资料,主要有两种风格的iterative solution for binary tree traversal

For example, for the preorder traversal, there are two kinds of iterative solutions. Pay attention to the condition of the while loop:

https://leetcode.com/problems/binary-tree-preorder-traversal/

1.指针遍历同时压栈根节点法 while(root!=null||!s.isEmpty()):

http://blog.youkuaiyun.com/linhuanmars/article/details/21428647

List<Integer> res = new ArrayList<Integer>();
while(root!=null||!s.isEmpty()){
            if(root!=null){
                res.add(root.val);
                s.push(root);
                root = root.left;
            }
            else{
                TreeNode n = s.pop();
                root = n.right;
                
            }
        }
        return res;
2. 先压栈子节点后弹栈遍历法while(!s.isEmpty()):

https://algorithm.yuanbin.me/zh-hans/binary_tree/binary_tree_preorder_traversal.html

        List<Integer> res = new ArrayList<Integer>();        
        if(root==null){
            return res;
        }
        LinkedList<TreeNode> s = new LinkedList<TreeNode>();
        s.push(root);
        while(!s.isEmpty()){
            TreeNode n = s.pop();
            res.add(n.val);
            if(n.right!=null){
                s.push(n.right);
            }
            if(n.left!=null){
                s.push(n.left);
            }
            
        }
        return res;

本来我觉得第二种方法好一些,但后来发现inorder用第二种方法很难做。所以为了统一记忆方便,还是都选用第一种只压栈根节点做法吧!

转载于:https://my.oschina.net/u/1766462/blog/793977

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值