0102. Binary Tree Level Order Traversal (M)

0102. Binary Tree Level Order Traversal (M)

题目

Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).

For example:

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

		3
   / \
  9  20
    /  \
   15   7

return its level order traversal as:

[
  [3],
  [9,20],
  [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<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> ans = new ArrayList<>();
        Queue<TreeNode> q = new ArrayDeque<>();

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

        while (!q.isEmpty()) {
            List<Integer> 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);
            }
            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 levelOrder = function (root) {
  const ans = []
  const q = []
  if (root) q.push(root)

  while (q.length) {
    const size = q.length
    const tmp = []
    for (let i = 0; i < size; i++) {
      const cur = q.shift()
      if (cur.left) q.push(cur.left)
      if (cur.right) q.push(cur.right)
      tmp.push(cur.val)
    }
    ans.push(tmp)
  }

  return ans
}
posted @ 2021-05-20 20:55  墨云黑  阅读(25)  评论(0编辑  收藏  举报