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

求二叉树的层序遍历

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

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

class Solution {
public:
    /**
     * 
     * @param root TreeNode类 
     * @return int整型vector<vector<>>
     */
    vector<vector<int>>  res;
    vector<int> tmp;
    vector<vector<int> > levelOrder(TreeNode* root) {
        // write code here
        if(!root) return res;
        queue<TreeNode*> q;
        q.push(root);
        q.push(NULL);
        while(q.size()){
            auto t = q.front();
            q.pop();
            
            if(t){
                tmp.push_back(t->val);
                if(t->left) q.push(t->left);
                if(t->right) q.push(t->right);
            }else{
                res.push_back(tmp);
                tmp.clear();
                if(q.size()) q.push(NULL);
                
            }
        }
        return res;
    }
};
全部评论

相关推荐

在打卡的大老虎很想潜...:你在找实习,没啥实习经历,技术栈放前面,项目多就分两页写,太紧凑了,项目你最多写两个,讲清楚就行,项目背景。用到的技术栈、亮点、难点如何解决,人工智能进面太难了,需求少。你可以加最新大模型的东西
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

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