Easy understand cpp solution by a beginner


  • 0
    Z
    class Solution {
    public:
    void connect(TreeLinkNode *root) {
        if(root==NULL)
        return ;
        
        vector<TreeLinkNode*> nodes;
    	vector<int> level;
    	int head=0,tail=1;
    	nodes.push_back(root);
    	level.push_back(0);
    	while(head<tail){
    		if(nodes[head]->left!=NULL){
    			nodes.push_back(nodes[head]->left);
    			nodes.push_back(nodes[head]->right);
    			level.push_back(level[head]+1);
    			level.push_back(level[head]+1);
    			tail+=2;
    		}
    		head++;
    	}
    	
    	for(int i=0;i<nodes.size()-1;i++){
    		if(level[i]==level[i+1])
    			nodes[i]->next = nodes[i+1];
    	}
    }
    };

Log in to reply
 

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