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

Populating Next Right Pointers in Each Node II

2015-02-03 15:18 417 查看
https://oj.leetcode.com/submissions/detail/15044874/

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


public void connect(TreeLinkNode root)

这一题由于constant extra space的限制导致了BFS的无法使用,准确来说,是我们平常的BFS无法使用。但这一题,树节点的特殊性,导致我们可以在constant space的情况下,依旧做到BFS。简单来说就是利用爸爸溜儿子。假如,我们已经有了一层连好的节点,然后我们有这一层节点的从左到右方向的开头,事实上,我们就可以把这一层节点的儿子节点都走完了,也就是下一层就可以被走完并且连好了(就是从左到右不停next的同时把left right都访问了)。然后下一层的儿子又当爸爸了,就能够继续这个过程直到结束了。

constant space的算法核心就是这个理念,就这样利用一层已经next好的层级一层一层往下连接。下面给出答案代码:

public void connect(TreeLinkNode root) {
TreeLinkNode prev_leftmost = root, cur_level = null, prev = null;
while(prev_leftmost != null){//这里命名有点问题,应该是cur_leftmost
cur_level = prev_leftmost;
prev_leftmost = null;
prev = null;
while(cur_level != null){
prev_leftmost = prev_leftmost != null ? prev_leftmost : cur_level.left;//
prev_leftmost = prev_leftmost != null ? prev_leftmost : cur_level.right;//这两行是在找下一层的“链表”头
if(cur_level.left != null){//下面一个个连
if(prev != null){
prev.next = cur_level.left;
}
prev = cur_level.left;
}
if(cur_level.right != null){
if(prev != null){
prev.next = cur_level.right;
}
prev = cur_level.right;
}
cur_level = cur_level.next;//当前这一层“链表”往下走
}
}

}


2018-01-09 Updated: 思考了一下,觉得上述代码存在一定的冗余性,而且两个while loop看起来代码可读性也不是那么高。下面给出只有一个while loop而且稍微提高了代码重用性的代码

public void connect(TreeLinkNode root) {
TreeLinkNode currentNode = root;
TreeLinkNode[] nextLevel = new TreeLinkNode[1];
TreeLinkNode[] prev = new TreeLinkNode[1];
while (currentNode != null) {
_tryConnectNext(currentNode.left, nextLevel, prev);
_tryConnectNext(currentNode.right, nextLevel, prev);
currentNode = currentNode.next;
if(currentNode == null) {
currentNode = nextLevel[0];
nextLevel[0] = null;
prev[0] = null;
}
}
}

private void _tryConnectNext(TreeLinkNode node, TreeLinkNode[] nextLevel, TreeLinkNode[] prev) {
if (node != null) {
if (prev[0] == null) {
prev[0] = node;
} else {
prev[0].next = node;
prev[0] = prev[0].next;
}

if (nextLevel[0] == null) {
nextLevel[0] = node;
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: