leetcode -- Populating Next Right Pointers in Each Node
Given a binary tree
struct TreeLinkNode { TreeLinkNode *left; TreeLinkNode *right; TreeLinkNode *next; }
Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set toNULL
.
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).
For example,
Given the following perfect binary tree,
1 / \ 2 3 / \ / \ 4 5 6 7
After calling your function, the tree should look like:
1 -> NULL / \ 2 -> 3 -> NULL / \ / \ 4->5->6->7 -> NULL
[解题思路]
对二叉树使用层序遍历,层序遍历过程使用两个queue来分层
1 /** 2 * Definition for binary tree with next pointer. 3 * public class TreeLinkNode { 4 * int val; 5 * TreeLinkNode left, right, next; 6 * TreeLinkNode(int x) { val = x; } 7 * } 8 */ 9 public class Solution { 10 public void connect(TreeLinkNode root) { 11 // Start typing your Java solution below 12 // DO NOT write main() function 13 if(root == null){ 14 return; 15 } 16 17 levelOrderTraverse(root); 18 } 19 20 public void levelOrderTraverse(TreeLinkNode node){ 21 LinkedList<TreeLinkNode> first = new LinkedList<TreeLinkNode>(); 22 LinkedList<TreeLinkNode> second = new LinkedList<TreeLinkNode>(); 23 first.add(node); 24 while(!first.isEmpty()){ 25 TreeLinkNode tmp = first.poll(); 26 if(tmp.left != null){ 27 second.add(tmp.left); 28 } 29 if(tmp.right != null){ 30 second.add(tmp.right); 31 } 32 if(first.isEmpty()){ 33 tmp.next = null; 34 first.addAll(second); 35 second.clear(); 36 } else { 37 tmp.next = first.peek(); 38 } 39 } 40 } 41 }
updated
由于题目中要求只能使用constant space,所以上面使用两个queue做法是不对的
1 -> NULL / \ 2 -> 3 -> NULL / \ / \ 4->5->6->7 -> NULL
这题主要的难点在于处理节点5的next,因为5的next要指向它的sibling,但在5这层是没法获取到3的引用
解决方法是:由于2所在那层已经建立好next链接,所以只需由2即可得到3的引用,继而得到3的left节点
1 public void connect(TreeLinkNode root) { 2 // Start typing your Java solution below 3 // DO NOT write main() function 4 if(root == null){ 5 return; 6 } 7 if(root.left != null){ 8 root.left.next = root.right; 9 } 10 if(root.right != null){ 11 root.right.next = (root.next != null) ? root.next.left : null; 12 } 13 14 connect(root.left); 15 connect(root.right); 16 }