题解 | #求二叉树的层序遍历#

求二叉树的层序遍历

https://www.nowcoder.com/practice/04a5560e43e24e9db4595865dc9c63a3

/**
 * struct TreeNode {
 *	int val;
 *	struct TreeNode *left;
 *	struct TreeNode *right;
 * };
 */

#include <vector>
class Solution {
public:
    vector<vector<int>> findAll(vector<TreeNode*> vec){
        vector<vector<int>> res;
        if(vec.empty()) return res;
        vector<int> current;
        vector<TreeNode*> next;
        for(int i = 0;i < vec.size();i++){
            current.push_back(vec[i]->val);
            if(vec[i]->left != nullptr){
                next.push_back(vec[i]->left);
            }
            if(vec[i]->right != nullptr){
                next.push_back(vec[i]->right);
            }
        }
        res.push_back(current);
        vector<vector<int>> vec1 = findAll(next);
        for(vector<int> v1:vec1){
            res.push_back(v1);
        }
        return res;
    }
    /**
     * 
     * @param root TreeNode类 
     * @return int整型vector<vector<>>
     */
    vector<vector<int>> levelOrder(TreeNode* root) {
        // write code here
        vector<vector<int>> res;
        if(root == nullptr) return res;
        vector<int> first;
        first.push_back(root->val);
        res.push_back(first);
        vector<TreeNode*> vec;
        if(root->left != nullptr){
            vec.push_back(root->left);
        }
        if(root->right != nullptr){
            vec.push_back(root->right);
        }
        vector<vector<int>> next = findAll(vec);
        for(vector<int> v1:next){
            res.push_back(v1);
        }
        return res;
    }
};

全部评论

相关推荐

07-15 18:09
门头沟学院 Java
点赞 评论 收藏
分享
05-29 22:11
门头沟学院 Java
Elastic90:抛开学历造假不谈,这公司的招聘需求也挺怪的,Java开发还要求你有图文识别、移动端开发和c++的经验,有点逆天了。
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务