Problem Populating Next Right Pointers in Each Node II
2014-06-29 15:05
344 查看
Problem Description:
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,
After calling your function, the tree should look like:
Solution:
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
Solution:
public void connect(TreeLinkNode root) { if (root == null) { return; } TreeLinkNode cur = root.next; TreeLinkNode p = null; while (cur != null) { if (cur.left != null) { p = cur.left; break; } if (cur.right != null) { p = cur.right; break; } cur = cur.next; } if (root.right != null) { root.right.next = p; } if (root.left != null) { root.left.next = root.right != null ? root.right : p; } connect(root.right); connect(root.left); }
相关文章推荐
- 【遍历二叉树】12往二叉树中添加层次链表的信息【Populating Next Right Pointers in Each Node II】
- LeetCode_Tree_Populating Next Right Pointers in Each Node I II
- 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
- (M)DFS: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
- Populating Next Right Pointers in Each Node I, 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 II
- [LeetCode#117]Populating Next Right Pointers in Each Node II
- [LeetCode]problem 117. Populating Next Right Pointers in Each Node II
- 117:Populating Next Right Pointers in Each Node II【树】【DFS】
- 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 I&&II
- Leetcode 117 Populating Next Right Pointers in Each Node II