Leetcode 103 Binary Tree Zigzag Level Order Traversal 层次遍历变形

题目表述

Given a binary tree, return the zigzag level order traversal of its nodes’ values. (ie, from left to right, then right to left for the next level and alternate between).

For example:
Given binary tree [3,9,20,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7

return its zigzag level order traversal as:

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

层次遍历

Level-Order Tranverse 也就是层次遍历,是树的最常见的遍历方式之一;层次遍历也是广度优先遍历的一个子集。这道题是层次遍历的一个变体,只需要在每一个层次中保存一个数组用于存储该层次的结点,在该层遍历结束之后,判断是否要reverse以及添加。

我们使用如下的数据结构来实现层次遍历:
List<TreeNode> Queue 用于保存每一层的结点
List<List<Integer>> result 用于实施更新结果

AC代码(>93.76%)

class Solution {
    public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
        List<TreeNode> queue = new ArrayList<>();
        List<List<Integer>> result = new ArrayList<>();
        if (root==null) return result;
        queue.add(root);
        int direct = 0;
        while (!queue.isEmpty()){
            List<Integer> addi = new ArrayList<>();
            int num = queue.size();
            for (int i=0;i<num;i++){
                TreeNode node = queue.remove(0);
                addi.add(node.val);
                if (node.left!=null) queue.add(node.left);
                if (node.right!=null) queue.add(node.right);
            }
            if (direct==0){
                result.add(addi);
            } else{
                Collections.reverse(addi);
                result.add(addi);
            }
            direct = 1 - direct;
        }
        return result;
    }
}


1 thought on “Leetcode 103 Binary Tree Zigzag Level Order Traversal 层次遍历变形”

Leave a Reply

Your email address will not be published. Required fields are marked *