二叉树广度优先算法(水平搜索),使用队列保存各节点,初步完成能编译通过代码:

/**
 * 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) {
        queue<TreeNode *> queue;
        vector<vector<int>> level;
        queue.push(root);
        
        while(!queue.empty())
        {
            vector<int> tmp;
            TreeNode * head = queue.front();
            tmp.push_back(head->val);
            
            if(head->left)
                queue.push(head->left);
            
            if(head->right)
                queue.push(head->right);
            
            queue.pop();
            level.push_back(tmp);
        }
        
        return level;
    }
};

运行结果:

Wrong Answer
Runtime: 0 ms
Your input
[3,9,20,null,null,15,7]
Output
[[3],[9],[20],[15],[7]]
Expected
[[3],[9,20],[15,7]]

WA的原因是我们没有在vector中按层次保存节点,而是每个结点一个vector,如何修复这个问题呢?
在while中添加for循环,每次进入while时先获取queue的大小,queue的大小就是当前层元素的个数。

/**
 * 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) {
        queue<TreeNode *> queue;
        vector<vector<int>> level;
        if(root) queue.push(root);
        
        while(!queue.empty())
        {
            vector<int> res;
            int n = queue.size();
            for(int i = 0;i < n;i++)
            {
                TreeNode * elem = queue.front();
                res.push_back(elem->val);
                if(elem->left) queue.push(elem->left);
                if(elem->right) queue.push(elem->right);
            
                queue.pop();
            }
            
            if(res.size() > 0)
                level.push_back(res);
        }
        
        return level;
    }
};

运行结果:

34 / 34 test cases passed.
Status: Accepted
Runtime: 0 ms
Memory Usage: 12.8 MB
Submitted: 1 minute ago