您的位置:首页 > Web前端 > Node.js

117. Populating Next Right Pointers in Each Node II

2016-09-30 15:35 441 查看
解题思路:

和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);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  dfs