首页 > 学院 > 开发设计 > 正文

Leetcode 117. Populating Next Right Pointers in Each Node II

2019-11-14 10:55:36
字体:
来源:转载
供稿:网友

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 7

After calling your function, the tree should look like:

1 -> NULL / / 2 -> 3 -> NULL / / /4-> 5 -> 7 -> NULL

s思路: 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; } } }};
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表