23ms c++ bfs solution


  • 0
    X
    class Solution {
    public:
        void connect(TreeLinkNode *root) {
            if(!root) return;
    		
    		//use bfs method, cound number of nodes at every level
    		queue<TreeLinkNode*> myqueue;
    		myqueue.push(root);
    		int currLevel = 1, nextLevel = 0;
    		int count = 0;
    		while(!myqueue.empty()){
    			TreeLinkNode* curr = myqueue.front();
    			myqueue.pop();
    			
    			//add its children to nextLevel
    			if(curr->left != nullptr){
    				myqueue.push(curr->left);
    				nextLevel++;
    			}
    			if(curr->right != nullptr){
    				myqueue.push(curr->right);
    				nextLevel++;
    			}
    			
    			//perform the link operation
    			currLevel --;
    			if(currLevel == 0){
    				currLevel = nextLevel;
    				nextLevel = 0;
    				curr->next = nullptr;
    			}
    			else{
    				curr->next = myqueue.front();
    			}
    			
    		}
        }
    };
    

Log in to reply
 

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