level order traversal o(n) memory o(n) time c++


  • 0

    class Solution {
    public:
    void connect(TreeLinkNode root) {
    queue<TreeLinkNode
    > q;
    if(root == NULL)
    return;
    q.push(root);
    while(!q.empty()){
    int s = q.size();
    vector<TreeLinkNode*> tmp_vec;
    for(int i = 0; i < s; i++){
    TreeLinkNode* top = q.front();
    q.pop();
    tmp_vec.push_back(top);
    if(top->left)
    q.push(top->left);
    if(top->right)
    q.push(top->right);
    }
    for(int i = 0; i < tmp_vec.size() - 1; i++){
    tmp_vec[i]->next = tmp_vec[i + 1];
    }
    }
    return;
    }
    };


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.