欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

leetcode117.填充每个节点的下一个右侧节点指针II

程序员文章站 2022-05-20 20:08:44
...

题目简述:

填充它的每个next指针,注意这里并不是完美二叉树。

class Solution {
public:
    Node* connect(Node* root) {
        if(root == nullptr) return root;
        vector<Node*> last_level;
        last_level.push_back(root);
        vector<Node*> now_level;
        while(last_level.size() != 0) {
            now_level.clear();
            for(auto node:last_level) {
                if(node->left != nullptr) {
                    now_level.push_back(node->left);
                }
                if(node->right != nullptr) {
                    now_level.push_back(node->right);
                }
            }
            if(now_level.size() != 0) {
                for(int i = 0; i < now_level.size()-1; i++) {
                    now_level[i]->next = now_level[i+1];
                }
            }
            last_level.clear();
            auto iter = last_level.insert(end(last_level), begin(now_level), end(now_level));
        }
        return root;
    }
};

注意在18行加了一个now_level.size() != 0的判断语句,

不知道为什么这样会报错?望网友解答

for(int i = 0; i < -1; i++) {
    cout<<now_level[i]->val; // 报错
}