117. Populating Next Right Pointers in Each Node II
来源:互联网 发布:中央电视台软件下载 编辑:程序博客网 时间:2024/06/06 04:15
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
复杂度:时间 O(N) 空间 O(1)
思路:
第一问层次递进的延伸。上一问中我们不需要一个额外的指针来控制我们一层中链接的节点,因为我们知道肯定是左右左右的顺序,而这题中左右节点可能不存在,所有我们要用一个指针记录这一层中我们链接到了哪个节点,方便我们链接下一个节点。
/** * Definition for binary tree with next pointer. * public class TreeLinkNode { * int val; * TreeLinkNode left, right, next; * TreeLinkNode(int x) { val = x; } * } */public class Solution { public void connect(TreeLinkNode root) { // head是上一层的节点,我们用上一层节点的next形成链表,来链接当前这层 TreeLinkNode head = root; while(head != null){ // 记录链接到哪个节点的额外指针 TreeLinkNode curr = new TreeLinkNode(0); // tmp指向该层的第一节点 TreeLinkNode tmp = curr; while(head != null){ // 尝试链接左节点 if(head.left != null){ curr.next = head.left; curr = curr.next; } // 尝试链接右节点 if(head.right != null){ curr.next = head.right; curr = curr.next; } head = head.next; } // 将head移动到当前这层的的第一个,准备链接下一层 head = tmp.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
- 117. Populating Next Right Pointers in Each Node II
- [leetcode] 117.Populating Next Right Pointers in Each Node II
- 116. Populating Next Right Pointers in Each Node && 117. 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
- 117. Populating Next Right Pointers in Each Node II
- LeetCode 117. Populating Next Right Pointers in Each Node II
- 117. Populating Next Right Pointers in Each Node II
- 117. Populating Next Right Pointers in Each Node II
- Leetcode 117. Populating Next Right Pointers in Each Node II
- 117. Populating Next Right Pointers in Each Node II
- [LeetCode] 117. Populating Next Right Pointers in Each Node II
- 117. Populating Next Right Pointers in Each Node II
- 117. Populating Next Right Pointers in Each Node II
- c++中boost协程5种使用实例
- 感悟:学编程语言就像学方言
- 在Centos7下捣鼓邮件发送软件sendmail与postfix
- 对于AOP的简单理解:AOP的含义及作用
- Apache默认虚拟主机
- 117. Populating Next Right Pointers in Each Node II
- [使用教程]xftp5中文版怎么使用?
- python 错误处理 assert
- Web 开发中的接口定义总结
- 获取XML文件内容
- 机器学习中的数学(10)——奇异值分解(SVD)及其应用
- Android 开源框架 SwipeDragTreeRecyclerView 使用说明
- CentOS7安装
- 【python初识】列表与函数模块