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

求二叉树的层序遍历

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;
    }
};
全部评论

相关推荐

AAA专业长城贴瓷砖刘大爷:这样的简历我会直接丢进垃圾桶,花里胡哨的
点赞 评论 收藏
分享
求offer的大角牛:不吃香菜
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

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