Leetcode:102. 二叉树的层次遍历

给定一个二叉树,返回其按层次遍历的节点值。 (即逐层地,从左到右访问所有节点)。

例如:
给定二叉树: [3,9,20,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7

返回其层次遍历结果:

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

解题思路:

广度优先搜索(BFS)。

Leetcode:102. 二叉树的层次遍历

C++代码
class Solution {
public:
    vector<vector<int>> levelOrder(TreeNode* root) {
        vector<vector<int>> res;
        if (root == NULL) return res;
        queue<TreeNode*> Q;
        TreeNode* node;
        vector<int> res1;
        Q.push(root);
        while (!Q.empty()) {
            int size = Q.size();
            res1.clear();
            for (int i = 1; i <= size; i++) {
                node = Q.front();
                res1.push_back(node->val);
                if (hasLChild(node)) { Q.push(node->left); }
                if (hasRChild(node)) { Q.push(node->right); }
                Q.pop();
            }
            res.push_back(res1);
        }
        return res;
    }
};