[LeetCode] 102. Binary Tree Level Order Traversal

Given the root of a binary tree, return the level order traversal of its nodes' values. (i.e., from left to right, level by level).
Example1:

Input: root = [3,9,20,null,null,15,7]
Output: [[3],[9,20],[15,7]]

Example2:

Input: root = [1]
Output: [[1]]

Example3:

Input: root = []
Output: []

Constraints:

  • The number of nodes in the tree is in the range [0, 2000].
  • -1000 <= Node.val <= 1000

这道题是典型的宽度有限搜索。要用Queue来解决,分层则是靠Queue的size。只要Queue不为空,就一直循环下去。

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> rst = new ArrayList<>();
        if (root == null) {
            return rst;
        }
        
        Queue<TreeNode> pq = new LinkedList<TreeNode>();
        pq.add(root);
        
        while (!pq.isEmpty()) {
            int n = pq.size();
            List<Integer> levelNode = new ArrayList<>();
            for (int i = 0; i < n; i++) {
                TreeNode node = pq.poll();
                levelNode.add(node.val);
                if (node.left != null) {
                    pq.add(node.left);
                }
                if (node.right != null) {
                    pq.add(node.right);
                }
            }
            rst.add(levelNode);
        }
        return rst;
    }
}
上一篇:111.二叉树的最小深度


下一篇:【Leetcode】NO.637 二叉树的层平均值 (C++&Python) [二叉树]