Follow up for PRoblem “Populating Next Right Pointers in Each Node”.
What if the given tree could be any binary tree? Would your previous solution still work?
Note:
You may only use constant extra space. For example, Given the following binary tree,
1 / / 2 3 / / /4 5 7After calling your function, the tree should look like:
1 -> NULL / / 2 -> 3 -> NULL / / /4-> 5 -> 7 -> NULLs思路: 1. o(1)的空间,注定只能用iterative的方法了。参考https://discuss.leetcode.com/topic/1106/o-1-space-o-n-complexity-iterative-solution/6 2. 由于不规则的树结构,所以需要用pre,cur来找到新的连接关系的两端;还需要一个head表示每层的起点。三个指针的interplay在代码里面写得很清楚。每次把head赋给cur,然后根据cur->left、cur->right是否存在来更新连接:如果cur->left存在,又看pre是否已经存在:不存在则这个节点就是head,且pre=cur->left;存在则就把这个节点作为pre的next;对cur->right也同样判断。 3. 多体会!
//class Solution {public: void connect(TreeLinkNode *root) { // TreeLinkNode* horizon=NULL,*vertical=root; TreeLinkNode* head=root,*cur=NULL,*pre=NULL; while(head){ cur=head; pre=NULL; head=NULL; while(cur){ if(cur->left){ if(!pre){ head=cur->left; pre=head; }else{ pre->next=cur->left; pre=pre->next; } } if(cur->right){ if(!pre){ head=cur->right; pre=head; }else{ pre->next=cur->right; pre=pre->next; } } cur=cur->next; } } }};新闻热点
疑难解答