8 mins - Populating Next Right Pointers in Each Node II
2014-05-03 09:29
351 查看
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:
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
/** * 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) { if (root == null) { return ; } TreeLinkNode levelHead = root; while (levelHead != null) { TreeLinkNode levelIt = levelHead; TreeLinkNode newLevelIt = null; TreeLinkNode newLevelHead = null; while (levelIt != null) { if (levelIt.left != null) { if (newLevelIt != null) { newLevelIt.next = levelIt.left; } newLevelIt = levelIt.left; if (newLevelHead == null) { newLevelHead = levelIt.left; } } if (levelIt.right != null) { if (newLevelIt != null) { newLevelIt.next = levelIt.right; } newLevelIt = levelIt.right; if (newLevelHead == null) { newLevelHead = levelIt.right; } } levelIt = levelIt.next; } levelHead = newLevelHead; } } }
相关文章推荐
- [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 II @ Python
- LeetCode - Populating Next Right Pointers in Each Node II 及其变形题
- Populating Next Right Pointers in Each Node II
- LeetCode - 116/117 - Populating Next Right Pointers in Each NodeII
- 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] [LeetCode] Populating Next Right Pointers in Each Node II
- 【LeetCode】Populating Next Right Pointers in Each Node II
- leetcode 116:Populating Next Right Pointers in Each Node I And II
- [Leetcode] Populating Next Right Pointers in Each Node II
- LeetCode_Tree_Populating Next Right Pointers in Each Node I II
- ****(leetcode) Populating Next Right Pointers in Each Node II
- Problem 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
- Populating Next Right Pointers in Each Node II