Leetcode 117. Populating Next Right Pointers in Each Node II
来源:互联网 发布:网络用语orz是什么意思 编辑:程序博客网 时间:2024/06/05 08:18
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; } } }};
0 0
- LeetCode 117. Populating Next Right Pointers in Each Node II
- [LeetCode]117.Populating Next Right Pointers in Each Node II
- [Leetcode] 117. Populating Next Right Pointers in Each Node II
- [leetcode] 117.Populating Next Right Pointers in Each Node II
- [LeetCode]117. Populating Next Right Pointers in Each Node II
- Leetcode 117. Populating Next Right Pointers in Each Node II
- [leetcode]117. Populating Next Right Pointers in Each Node II
- LeetCode 117. Populating Next Right Pointers in Each Node II
- Leetcode 117. Populating Next Right Pointers in Each Node II
- [LeetCode] 117. Populating Next Right Pointers in Each Node II
- LeetCode 117. Populating Next Right Pointers in Each Node II
- leetcode-117. Populating Next Right Pointers in Each Node II
- Leetcode 117. Populating Next Right Pointers in Each Node II
- leetcode 117. Populating Next Right Pointers in Each Node II
- LeetCode 117. Populating Next Right Pointers in Each Node II
- leetcode 117. Populating Next Right Pointers in Each Node II
- [LeetCode] 117. Populating Next Right Pointers in Each Node II
- LeetCode#117. Populating Next Right Pointers in Each Node II
- 读完这个我懂了JNDI
- javascript:history.go()和History.back()的区别
- springmvc整合mybatis框架源码 bootstrap html5 mysql oracle maven SSM
- centos6.5克隆机器后更改IP地址
- ios新建target出包流程
- Leetcode 117. Populating Next Right Pointers in Each Node II
- python 编码问题
- 微信企业号no privilege to access/modify contact/party/agent
- Linux文件管理
- sphinx增量索引和主索引来实现索引的实时更新
- 新年抓包大礼包
- java 有前后台 springmvc SSM 生成静态化 企业网站源码模版
- Java 可变 数组 可变 参数 实例
- 【SSH进阶之路】【十二】hibernate5 注解映射【5】一对一共享主键关联