5.1.12 Populating Next Right Pointers in Each Node II
2014-07-16 03:37
211 查看
原题链接:https://oj.leetcode.com/problems/populating-next-right-pointers-in-each-node-ii/
假设原始的树如下:
方法I: 递归 Time O(n), Space O(1) ( 递归要用到栈,所以是O(1)吗?)
方法II: 迭代 (见leetcode上戴的代码。没看懂。)
另:http://n00tc0d3r.blogspot.com/2013/05/populating-next-right-pointers-for-each.html
假设原始的树如下:
方法I: 递归 Time O(n), Space O(1) ( 递归要用到栈,所以是O(1)吗?)
public class Solution { public void connect(TreeLinkNode root) { if(root == null) return; if(root.left != null){ root.left.next = root.right == null ? getNext(root) : root.right; } if(root.right != null){ root.right.next = getNext(root); } connect(root.right); connect(root.left); } private TreeLinkNode getNext(TreeLinkNode n){ TreeLinkNode cur = n; while(cur.next != null){ cur = cur.next; if(cur.left != null){ return cur.left; } if(cur.right != null){ return cur.right; } } return null; } }
方法II: 迭代 (见leetcode上戴的代码。没看懂。)
另:http://n00tc0d3r.blogspot.com/2013/05/populating-next-right-pointers-for-each.html
相关文章推荐
- 【LeetCode OJ】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 117 —— 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 I & II
- LeetCode:Populating Next Right Pointers in Each Node I II
- Populating Next Right Pointers in Each Node II
- Populating Next Right Pointers in Each Node I, II
- 117. Populating Next Right Pointers in Each Node II
- [LeetCode] [LeetCode] Populating Next Right Pointers in Each Node II
- 【LeetCode】Populating Next Right Pointers in Each Node II
- Populating Next Right Pointers in Each Node II
- LeetCode:Populating Next Right Pointers in Each Node I & II
- LeetCode(Oct28'12):Populating Next Right Pointers in Each Node II
- 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
- Populating Next Right Pointers in Each Node II
- ****(leetcode) Populating Next Right Pointers in Each Node II