AC code, a little bit wordy, but logic is more easy


  • 0
    C
    class Solution {
        public:
            	void connect(TreeLinkNode *root)
        	{
        		if(root==NULL) return;
        		TreeLinkNode * pre = NULL;
        		TreeLinkNode * cur = NULL;
        		TreeLinkNode * head = root;
        		while(head)
        		{
        			cur = head;
        			while(cur)
        			{
        				if(cur->left!=NULL)
        				{
        					if(pre!=NULL)
        					{
        						pre->next = cur->left;
        						pre = pre->next;
        					}
        					else
        					{
        						pre = cur->left;
        					}
        				}
        				if(cur->right!=NULL)
        				{
        					if(pre!=NULL)
        					{
        						pre->next = cur->right;
        						pre = pre->next;
        					}
        					else
        					{
        						pre = cur->right;
        					}
        				}
        				cur = cur->next;
        			}
        			if(head->left!=NULL) head = head->left;
        			else if(head->right != NULL) head = head ->right;
        			else
        			{
        			    while(head != NULL && head->left==NULL && head->right == NULL)
        			    {
        			        head = head->next;
        			    }
        			    if(head!=NULL && head->left != NULL) head = head ->left;
        			    else if(head!=NULL && head->right != NULL) head = head ->right;
        			}
        			pre = NULL;
        		}
        	}
        };
    

    The tail part is to update head to the next level, which needs a little bit more comparisons.


Log in to reply
 

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