思路1:递归
我们容易想到递归公式为:每一个节点的左孩子节点指向其右孩子
终止条件:节点不存在或者左孩子节点不存在直接返回
这么做没考虑跨节点的情况,比如节点5的next应该指向节点6。
完善:函数参数为两个
递归公式:node1.next=node2;
connect(node1.left,node1.right);connect(node2.left,node2.right);connect(node1.right,node2.left)
class Solution {
public Node connect(Node root) {
if(root==null)
{
return null;
}
connect(root.left,root.right);
return root;
}
private void connect(Node nLeft,Node nRight)
{
if(nLeft==null||nRight==null)
{
return;
}
nLeft.next=nRight;
connect(nLeft.left,nLeft.right);
connect(nRight.left,nRight.right);
connect(nLeft.right,nRight.left);
}
}
tip:递归的函数参数不只有一个,情况考虑周全