二叉树三种遍历,非递归,统一模板

1 难点

中序遍历,访问到某个节点时,不能直接输出他,要维护结点顺序。且目标是像递归实现一样有个统一模板,不同遍历顺序只需要调整几行代码的顺序。

2 思路

每个节点都访问两次,第一次压栈,第二次再输出。主需要注意压栈时候,自身、左、右的顺序。且每个中结点后面添加一个null结点作为标识待输出结点

3 先序

class Solution {
    public List<Integer> preorderTraversal(TreeNode root) {
        List<Integer> ans = new ArrayList<>();
        if(root==null){
            return ans;
        }
        Deque<TreeNode> q = new LinkedList<>();
        q.addLast(root);
        while(!q.isEmpty()){
            root=q.removeLast();
            if(root!=null){
                if(root.right!=null){
                    q.addLast(root.right);
                }
                if(root.left!=null){
                    q.addLast(root.left);
                }
                q.addLast(root);
                q.addLast(null);
            }else{//null前面一个就是要进答案数组的
                root=q.removeLast();
                ans.add(root.val);
            }
        }
        return ans;
    }
}

先序遍历是自身、左、右。压栈的时候就反过来,右、左、自身

4 中序

class Solution {
    public List<Integer> inorderTraversal(TreeNode root) {
        List<Integer> ans = new ArrayList<>();
        if(root==null){
            return ans;
        }
        Deque<TreeNode> q = new LinkedList<>();
        q.addLast(root);
        while(!q.isEmpty()){
            root=q.removeLast();
            if(root!=null){
                if(root.right!=null){
                    q.addLast(root.right);
                }
                q.addLast(root);
                q.addLast(null);
                if(root.left!=null){
                    q.addLast(root.left);
                }
            }else{//null前面一个就是要进答案数组的
                root=q.removeLast();
                ans.add(root.val);
            }
        }
        return ans;
    }
}

左、中、右–>右、中、左

5 后序

class Solution {
    public List<Integer> postorderTraversal(TreeNode root) {
        List<Integer> ans = new ArrayList<>();
        if(root==null){
            return ans;
        }
        Deque<TreeNode> q = new LinkedList<>();
        q.addLast(root);
        while(!q.isEmpty()){
            root=q.removeLast();
            if(root!=null){
                q.addLast(root);
                q.addLast(null);
                if(root.right!=null){
                    q.addLast(root.right);
                }
                if(root.left!=null){
                    q.addLast(root.left);
                }
            }else{//null前面一个就是要进答案数组的
                root=q.removeLast();
                ans.add(root.val);
            }
        }
        return ans;
    }
}

左、右、中–>中、右、左

  • 8
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值