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

leedcode做题总结,题目Populating Next Right Pointers in Each NodeI/II---------- 2012/10/28

2014-07-09 18:46 344 查看
这个题可以用先序递归,每个节点把两个儿子连起来,

注意的是每个节点还要把两个子树的每一层连起来,所以我用while来访问子树每一层最边的节点。

public void connect(TreeLinkNode root) {
if(root!=null){
if(root.left!=null&&root.right!=null){
root.left.next=root.right;
TreeLinkNode m =root.left;
TreeLinkNode n = root.right;
while (m.right!=null){
m.right.next=n.left;
m=m.right;
n=n.left;
}
}

connect(root.left);
connect(root.right);

}
}


由于第一题的思维定势,第二题没想出来,于是参考了别人的代码,使用广度优先历遍,用m记录每一行的第一个,然后让root以它为起点一次next移动,然后用n一次历遍子节点,链接全部子节点。

public static void conn(TreeLinkNode r){
TreeLinkNode m=null;
TreeLinkNode n=null;
while (r!=null){
if(r.left!=null){
if(m==null){
m=r.left;
n=r.left;
}else{
n.next=r.left;
n=r.left;
}

}
if(r.right!=null){
if(m==null){
m=r.right;
n=r.right;
}else{
n.next=r.right;
n=r.right;
}

}
r=r.next;
}
if(m!=null)
conn(m);
}
public void connect(TreeLinkNode root) {
conn(root);
}


Update 2015/08/17:

public class Solution {
public void connect(TreeLinkNode root) {
if (root == null)
return;
TreeLinkNode l = root.left;
TreeLinkNode r = root.right;
while (l != null && r != null){
l.next = r;
l = l.right;
r = r.left;
}
connect(root.left);
connect(root.right);
}
}


第二道题只需要每次递归最左边的,由于上一行均有next相连,所以我们通过历遍上一行来历遍下一行。

public class Solution {
public void connect(TreeLinkNode root) {
if (root == null)
return;
TreeLinkNode m = null;
TreeLinkNode n = null;
while (root != null){
if (root.left != null){
if (m == null){
m = root.left;
n = root.left;
} else {
n.next = root.left;
n = n.next;
}
}
if (root.right != null){
if (m == null){
m = root.right;
n = root.right;
} else {
n.next = root.right;
n = n.next;
}
}
root = root.next;
}
connect(m);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: