Populating Next Right Pointers in Each Node
2015-03-04 15:36
281 查看
Populating Next Right Pointers in Each Node
问题:
each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to
Initially, all next pointers are set to
Note:
You may only use constant extra space.
You may assume that it is a perfect binary tree (ie, all leaves are at the same level, and every parent has two children)
思路:
采用队列方法,poll队首的同时,加入两个其孩子
核心是记录每一个层次的大小,两层循环,时间复杂度为O(n)
我的代码:
View Code
学习之处:
自己的方法不足之处在于空间复杂度为O(n),而他人方法的空间复杂度为O(1)
他人方法的思路为使用2个循环,一个指针P1专门记录每一层的最左边节点,另一个指针P2扫描本层,把下一层的链接上
问题:
each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to
NULL.
Initially, all next pointers are set to
NULL.
Note:
You may only use constant extra space.
You may assume that it is a perfect binary tree (ie, all leaves are at the same level, and every parent has two children)
思路:
采用队列方法,poll队首的同时,加入两个其孩子
核心是记录每一个层次的大小,两层循环,时间复杂度为O(n)
我的代码:
public void connect(TreeLinkNode root) { if (root == null) { return; } TreeLinkNode leftEnd = root; while (leftEnd != null && leftEnd.left != null) { TreeLinkNode cur = leftEnd; while (cur != null) { cur.left.next = cur.right; cur.right.next = cur.next == null ? null: cur.next.left; cur = cur.next; } leftEnd = leftEnd.left; } }
View Code
学习之处:
自己的方法不足之处在于空间复杂度为O(n),而他人方法的空间复杂度为O(1)
他人方法的思路为使用2个循环,一个指针P1专门记录每一层的最左边节点,另一个指针P2扫描本层,把下一层的链接上
相关文章推荐
- leetcode JAVA Populating Next Right Pointers in Each Node 难度系数3 3.41
- 【LeetCode】Populating Next Right Pointers in Each Node(I and II)
- Populating Next Right Pointers in Each Node
- leetcode 116/117 Populating Next Right Pointers in Each Node 1/2
- 【LeetCode】Populating Next Right Pointers in Each Node
- leetcode-116. Populating Next Right Pointers in Each Node
- Populating Next Right Pointers in Each Node II
- LeetCode[Tree]: Populating Next Right Pointers in Each Node II
- LeetCode-Populating Next Right Pointers in Each Node
- LeetCode_Tree_Populating Next Right Pointers in Each Node I II
- Leetcode-116. Populating Next Right Pointers in Each Node
- Populating Next Right Pointers in Each Node
- LeetCode – Refresh – Populating Next Right Pointers in Each Node I and II
- leetcode@ [116/117] Populating Next Right Pointers in Each Node I & II (Tree, BFS)
- Leetcode 之Populating Next Right Pointers in Each Node II(51)
- Populating Next Right Pointers in Each Node I&II
- leetcode:Populating Next Right Pointers in Each Node
- Populating Next Right Pointers in Each Node
- Leetcode 117 Populating Next Right Pointers in Each Node II 二叉树填充next指针指向右侧结点 II
- leetcode--Populating Next Right Pointers in Each Node