leetcode102 二叉树的层次遍历

每层结束之后压如一个空的指针作为标志,最好不要压入NULL,代码如下

class Solution {
public:
    vector<vector<int> > levelOrder(TreeNode* root) {
        queue<TreeNode*> q;
        vector<vector<int>> ret;
        vector<int> tem;
        TreeNode * nothing = new TreeNode(0);//压如一个空的指针表示一行结束
        if(root!=NULL){
            q.push(root);
            q.push(nothing);
        }
        while(!q.empty()){
            TreeNode* temp = q.front();
            q.pop();
            if(temp==nothing ){
                if(q.size()>0){
                    q.push(nothing);
                }
                ret.push_back(tem);
                tem.clear();
            }else{
                if(temp!=nothing){
                    tem.push_back(temp->val);
                }
                if(temp->left)
                q.push(temp->left);
                if(temp->right)
                q.push(temp->right);

            }

        }
        return ret;
    }
};

猜你喜欢

转载自blog.csdn.net/L1558198727/article/details/81462805