解题思路:
和Populating Next Right Pointers in Each Node(https://leetcode.com/problems/populating-next-right-pointers-in-each-node/)一样采用dfs,但是注意在dfs的时候需要多做一些next节点是否存在的判断。并且需要注意的是,DFS时要先遍历right son, 再遍历left son。
如下例:
2
1 3
0 7 9 1
1 1 0 8 8
若先搜索left son,再搜索right son,在遍历到值为7的节点,9->1的next连接还没有建立。
代码如下:
public class Solution {
//most right son in the next generation
public TreeLinkNode mostRightSon(TreeLinkNode root){
if (root == null)
return null;
else
return (root.right == null) ? root.left : root.right;
}
//most left son of root.next(or root.next.next...) in the next generation
public TreeLinkNode mostLeftSon(TreeLinkNode root){
TreeLinkNode node = root;
while(node != null){
if (node.left != null)
return node.left;
else if (node.right != null)
return node.right;
else
node = node.next;
}
return null;
}
public void connect(TreeLinkNode root) {
if (root == null)
return;
if (root.left != null && root.right != null){
root.left.next = root.right;
}
TreeLinkNode mostRightSon = mostRightSon(root);
if (mostRightSon != null){
mostRightSon.next = mostLeftSon(root.next);
}
//root.right must be processed before left, because this is a depth first search so that the next of your right cousin may not have been processed.
connect(root.right);
connect(root.left);
}
}