二叉树的锯齿形遍历

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

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

3

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

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

链接:https://leetcode-cn.com/problems/binary-tree-zigzag-level-order-traversal

本题思路较为简单,仅为二叉树的层序遍历的变式,而要完成这一点仅需要设置一个记录当前层级的变量,当其为偶数时将当前层次遍历结果倒置即可,要达到这一点,仅需要一个辅助数组即可。

public List<List<Integer>> zigzagLevelOrder(TreeNode root) {

        List<List<Integer>> ans = new ArrayList();
        int count = 1;
        if (root == null)
            return ans;

        Queue<TreeNode> docker = new LinkedList<>();
        docker.offer(root);
        while (docker.size() != 0) {
            ArrayList<Integer> temp = new ArrayList();
            int[] arr = new int[docker.size()];
            int num = docker.size();
            for (int i = 0; i < num; i++) {
                TreeNode p=docker.poll();
                arr[i] =p.val;
                if (p.left != null)
                    docker.offer(p.left);
                if (p.right != null)
                    docker.offer(p.right);
            }
            if (count % 2 == 1) {
                for (int i = 0; i < arr.length; i++) {
                    temp.add(arr[i]);
                }
            } else {
                for (int i = arr.length - 1; i >= 0; i--) {
                    temp.add(arr[i]);
                }
            }
            count++;
            ans.add(temp);
        }
        return ans;
    }
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容