[LeetCode]Populating Next Right Pointers in Each Node II
来源:互联网 发布:tuneskit for windows 编辑:程序博客网 时间:2024/06/07 09:27
Question
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
本题难度Hard。
层次递进法
【复杂度】
时间 O(2^h-1) 空间 O(1)
【思路】
本题与[LeetCode]Populating Next Right Pointers in Each Node不一样的地方在于节点可以少儿子或没儿子。还是利用父节点层来链接子节点层,链接子节点时利用cur
代表需要链接的节点。在这里需要用一点技巧,就是用fake
来处理子节点层的第一个节点。如下图,last
指向的是父节点层的节点。
last 1 -> NULL \ / \ 2 -> 3 -> NULL 父节点层 \ \ fake-> 4 -> 5 -> NULL 子节点层 | cur
【代码】
public class Solution { public void connect(TreeLinkNode root) { //require TreeLinkNode last=root; //invariant while(last!=null){ TreeLinkNode fake=new TreeLinkNode(0); TreeLinkNode cur=fake; //遍历父节点层 while(last!=null){ // 尝试链接左节点 if(last.left!=null){ cur.next=last.left; cur=cur.next; } // 尝试链接右节点 if(last.right!=null){ cur.next=last.right; cur=cur.next; } last=last.next; } // 遍历完后,将last移动到子节点层的第一个,准备链接下一层 last=fake.next; } }}
参考
[Leetcode] Populating Next Right Pointers in Each Node 二叉树Next指针
0 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 II
- [Leetcode] Populating Next Right Pointers in Each Node II
- [LeetCode] Populating Next Right Pointers in Each Node II
- leetcode 79: 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 II
- 【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 II
- 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 II
- 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 II
- 【LeetCode OJ】Populating Next Right Pointers in Each Node II
- [LeetCode] Populating Next Right Pointers in Each Node II
- windows7下实现Bundler并通过cygwin编译运行以及pmvs、cmvs的使用(2)
- Dijkstra算法
- 清除浮动方法
- Hadoop/Yarn/MapReduce内存分配(解决Error:JVM heap space问题)
- 第四章 plsql控制语句
- [LeetCode]Populating Next Right Pointers in Each Node II
- Go基础知识
- 数据结构试验二 线性表实现(无头结点)
- 第十二周项目F参数宏定义进行弧度转换
- CSS格式化排版和元素分类
- MySQL设置主键自增
- HTML5-indexedDB使用常见错误总结
- 进制转换 这错误了
- 浅谈 View 的 OnTouchEvent 和 OnTouchListener 的区别