首页 > 其他 > 详细

leetcode 103. 二叉树的锯齿形层序遍历

时间:2021-04-22 15:59:07      阅读:32      评论:0      收藏:0      [点我收藏+]

给定一个二叉树,返回其节点值的锯齿形层序遍历。(即先从左往右,再从右往左进行下一层遍历,以此类推,层与层之间交替进行)。

例如:
给定二叉树 [3,9,20,null,null,15,7],

3
/ \
9 20
/ \
15 7
返回锯齿形层序遍历如下:

[
[3],
[20,9],
[15,7]
]

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/binary-tree-zigzag-level-order-traversal
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

 

采用层级遍历树的模式,只是使用了两个栈,每层交替使用,一个按照左右的顺序放,一个按照右左的顺序放。

    public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
        List<List<Integer>> all = new ArrayList<>();
        if (root == null) {
            return all;
        }
        Stack<TreeNode> a = new Stack<>();
        Stack<TreeNode> b = new Stack<>();
        a.add(root);
        List<Integer> item;
        while (!a.isEmpty() || !b.isEmpty()) {
            item = new ArrayList<>();
            while (!a.isEmpty()) {
                TreeNode pop = a.pop();
                item.add(pop.val);
                if (pop.left != null) {
                    b.add(pop.left);
                }
                if (pop.right != null) {
                    b.add(pop.right);
                }
            }
            if (!item.isEmpty()) {
                all.add(item);
            }
            item = new ArrayList<>();
            while (!b.isEmpty()) {
                TreeNode pop = b.pop();
                item.add(pop.val);
                if (pop.right != null) {
                    a.add(pop.right);
                }
                if (pop.left != null) {
                    a.add(pop.left);
                }
            }
            if (!item.isEmpty()) {
                all.add(item);
            }
        }
        return all;
    }

效率还可以。

技术分享图片

leetcode 103. 二叉树的锯齿形层序遍历

原文:https://www.cnblogs.com/wangzaiguli/p/14687914.html

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