0103. Binary Tree Zigzag Level Order Traversal (M)

Binary Tree Zigzag Level Order Traversal (M)

题目

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]
]

题意

按从上到下的顺序记录二叉树的每一层,但每一层的左右顺序与上一层相反。

思路

BFS,如果为偶数层则将该层的序列逆置。


代码实现

Java

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public List> zigzagLevelOrder(TreeNode root) {
        List> ans = new ArrayList<>();
        Queue q = new ArrayDeque<>();
        int level = 0;

        if (root != null) {
            q.offer(root);
        }

        while (!q.isEmpty()) {
            level++;
            List list = new ArrayList<>();
            int size = q.size();
            for (int i = 0; i < size; i++) {
                TreeNode cur = q.poll();
                list.add(cur.val);
                if (cur.left!=null) q.offer(cur.left);
                if (cur.right!=null) q.offer(cur.right);
            }
            if (level % 2 == 0) {
                Collections.reverse(list);
            }
            ans.add(list);
        }

        return ans;
    }
}

JavaScript

/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @return {number[][]}
 */
var zigzagLevelOrder = function (root) {
  let ans = []
  let q = []
  let leftToRight = true
  if (root) {
    q.push(root)
  }
  while (q.length) {
    let size = q.length
    let tmp = []
    while (size) {
      let cur = q.shift()
      if (cur.left) q.push(cur.left)
      if (cur.right) q.push(cur.right)
      if (leftToRight) {
        tmp.push(cur.val)
      } else {
        tmp.unshift(cur.val)
      }
      size--
    }
    leftToRight = !leftToRight
    ans.push(tmp)
  }
  return ans
}

你可能感兴趣的:(0103. Binary Tree Zigzag Level Order Traversal (M))