Leetcode P0102"Binary Tree Level Order Traversal" 题解

2020/09/03 Leetcode

博文中会简要介绍Leetcode P0102题目分析及解题思路。

“Binary Tree Level Order Traversal”是一道比较基础的树问题,层遍历一般使用广度优先搜索,即BFS,就可以解决。

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,可以使用队列来实现,对于遍历到每个树结点,分别将其左右子结点(非null)加入队列。由于队列的性质是FIFO,所以同一层的所有树结点一定是按从左到右的顺序依次出队列,直到盖层所有树结点都访问完了,才会进入下一层访问。这道题的难点并不在于BFS本身,而在于如何识别每一层的树结点,由于队列本身是连续的,不存在层与层之间有分隔,所以需要维护两个变量,分别代表当前层实际结点个数curr,和下一层的实际结点个数next,一旦当前层访问个数与curr值相同,则说明该层所有树结点已经访问完毕,这样一来就可以识别不同层的树结点,然后按层存储。

以下是Java的题解代码实现。

/**
 * 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>> levels = new ArrayList<>();
        if (root == null)
            return levels;
        
        Queue<TreeNode> queue = new LinkedList<>();
        List<Integer> level = new ArrayList<>();
        int numOfNodesInNextLevel = 0, numOfNodesInCurrentLevel = 1;
        
        queue.offer(root);
        while (!queue.isEmpty()) {
            TreeNode curr = queue.poll();
            
            if (curr.left != null) {
                queue.offer(curr.left);
                ++numOfNodesInNextLevel;
            }
            if (curr.right != null) {
                queue.offer(curr.right);
                ++numOfNodesInNextLevel;
            }
            
            level.add(curr.val);
            if (level.size() == numOfNodesInCurrentLevel) {
                levels.add(new ArrayList<>(level));
                level.clear();
                numOfNodesInCurrentLevel = numOfNodesInNextLevel;
                numOfNodesInNextLevel = 0;
            }
        }
        
        return levels;
    }
}

以下是C++的题解代码实现。

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    vector<vector<int>> levelOrder(TreeNode* root) {
        vector<vector<int>> levels;
        if (root == NULL)
            return levels;
        
        queue<TreeNode*> node_queue;
        vector<int> level;
        int num_in_curr_level = 1, num_in_next_level = 0;
        
        node_queue.push(root);
        while (!node_queue.empty()) {
            TreeNode *curr = node_queue.front();
            node_queue.pop();
            
            if (curr->left != NULL) {
                node_queue.push(curr->left);
                ++num_in_next_level;
            }
            if (curr->right != NULL) {
                node_queue.push(curr->right);
                ++num_in_next_level;
            }
            
            level.push_back(curr->val);
            if (level.size() == num_in_curr_level) {
                levels.push_back(vector<int>(level));
                level.clear();
                num_in_curr_level = num_in_next_level;
                num_in_next_level = 0;
            }
        }
        
        return levels;
    }
};

Search

    Table of Contents