Populating Next Right Pointers in Each Node -- LeetCode
来源:互联网 发布:u3软件 编辑:程序博客网 时间:2024/06/07 06:25
原题链接: http://oj.leetcode.com/problems/populating-next-right-pointers-in-each-node/
这道题是要将一棵树的每一层维护成一个链表,树本身是给定的。其实思路上很接近层序遍历Binary Tree Level Order Traversal,只是这里不需要额外维护一个队列。因为这里每一层我们会维护成一个链表,这个链表其实就是每层起始的那个队列,因此我们只需要维护一个链表的起始指针就可以依次得到整个队列了。接下来就是有左加左入链表,有右加右入链表,知道链表没有元素了说明到达最底层了。算法的复杂度仍然是对每个结点访问一次,所以是O(n),而空间上因为不需要额外空间来存储队列了,所以是O(1)。代码如下:
这道题是要将一棵树的每一层维护成一个链表,树本身是给定的。其实思路上很接近层序遍历Binary Tree Level Order Traversal,只是这里不需要额外维护一个队列。因为这里每一层我们会维护成一个链表,这个链表其实就是每层起始的那个队列,因此我们只需要维护一个链表的起始指针就可以依次得到整个队列了。接下来就是有左加左入链表,有右加右入链表,知道链表没有元素了说明到达最底层了。算法的复杂度仍然是对每个结点访问一次,所以是O(n),而空间上因为不需要额外空间来存储队列了,所以是O(1)。代码如下:
public void connect(TreeLinkNode root) { if(root == null) return; TreeLinkNode lastHead = root; TreeLinkNode pre = null; TreeLinkNode curHead = null; while(lastHead!=null) { TreeLinkNode lastCur = lastHead; while(lastCur != null) { if(lastCur.left!=null) { if(curHead == null) { curHead = lastCur.left; pre = curHead; } else { pre.next = lastCur.left; pre = pre.next; } } if(lastCur.right!=null) { if(curHead == null) { curHead = lastCur.right; pre = curHead; } else { pre.next = lastCur.right; pre = pre.next; } } lastCur = lastCur.next; } lastHead = curHead; curHead = null; }}这道题是树的层序遍历Binary Tree Level Order Traversal的扩展,操作上会更加繁琐一些,因为是通过维护层链表来完成遍历,不过本质上还是一次广度优先搜索。
55 0
- 【LeetCode】Populating Next Right Pointers in Each Node Populating Next Right Pointers in Each Node II
- leetcode Populating Next Right Pointers in Each Node &&Populating Next Right Pointers in Each Node||
- LeetCode Populating Next Right Pointers in Each Node & Populating Next Right Pointers in Each Node I
- 【Leetcode】Populating Next Right Pointers in Each Node in JAVA
- LeetCode Populating Next Right Pointers in Each Node
- LeetCode Populating Next Right Pointers in Each Node II
- [Leetcode] Populating Next Right Pointers in Each Node
- LeetCode: Populating Next Right Pointers in Each Node
- [Leetcode] Populating Next Right Pointers in Each Node II
- [LeetCode] Populating Next Right Pointers in Each Node
- [LeetCode] Populating Next Right Pointers in Each Node II
- 【leetcode】 Populating Next Right Pointers in Each Node
- leetcode 78: Populating Next Right Pointers in Each Node
- leetcode 79: Populating Next Right Pointers in Each Node II
- Leetcode: Populating Next Right Pointers in Each Node
- [Leetcode] Populating Next Right Pointers in Each Node ii
- leetcode Populating Next Right Pointers in Each Node II
- 【leetcode】Populating Next Right Pointers in Each Node
- iOS- 给App添加内购& 验证购买iOS7新特性
- Wget用法、参数解释
- LeetCode刷题笔录 Permutaions
- RotatedRect 可选择矩形 的绘制
- 黑马程序员_Foundation框架02_NSString
- Populating Next Right Pointers in Each Node -- LeetCode
- 黑马程序员_Foundation框架04_NSNumber、NSValue、NSDate
- 统计二进制数中1的个数
- USB设备不能用。提示Windows 无法启动这个硬件设备。 (代码 19)
- 磁通和磁通链,电感关系
- 广告术语:CPM、CPC、CPA、PFP、CPS、CPL、CPR介绍
- 利用WINPE修改本机系统注册表
- Use MusicBrainz in iOS(二)通过歌曲名查询信息
- OpenCV 例子代码的讲解、简介及库的安装