题目
方法1:广度优先搜索
深度优先搜索想半天想不出来,但是广度优先搜索仔细想就写出来了.....递归真的是玄学!
这个方法还蛮容易想得到的,借助一个队列就能完成。
/*
// Definition for a Node.
class Node {
public int val;
public Node left;
public Node right;
public Node next;
public Node() {}
public Node(int _val) {
val = _val;
}
public Node(int _val, Node _left, Node _right, Node _next) {
val = _val;
left = _left;
right = _right;
next = _next;
}
};
*/
class Solution {
public Node connect(Node root) {
// 2.广度优先搜索
if(root==null) return root;
Queue<Node> queue=new LinkedList<>();
int i=0,deep=1; // i计数,当前节点是第几个节点;deep计层数,当前是第几层
queue.offer(root);
while(!queue.isEmpty()){
Node node=queue.poll();
i++;
if(i==(int)(Math.pow(2,deep)-1)){ // 每层最后一个节点的next是null,其余节点的next都应该是队列queue的队头
node.next=null;
deep++;
}
else node.next=queue.peek(); //返回队列队头元素,但不删除;若不存在,则返回null
if(node.left!=null) queue.offer(node.left);
if(node.right!=null) queue.offer(node.right);
}
return root;
}
}
方法2:利用已建立的next指针
/*
// Definition for a Node.
class Node {
public int val;
public Node left;
public Node right;
public Node next;
public Node() {}
public Node(int _val) {
val = _val;
}
public Node(int _val, Node _left, Node _right, Node _next) {
val = _val;
left = _left;
right = _right;
next = _next;
}
};
*/
class Solution {
public Node connect(Node root) {
// 2.使用已建立的next指针,这个方法好高级!!
if(root==null) return root;
Node leftmost=root;
// node.next=null; //默认是null,所以可以不用写
while(leftmost.left!=null){ //注意判空leftmost.left
Node node=leftmost;
while(node!=null){
node.left.next=node.right;
if(node.next!=null) node.right.next=node.next.left;
node=node.next;
}
leftmost=leftmost.left;
}
return root;
}
}
方法3:深度优先搜索——递归
“别人的脑子是秀,我的脑子是锈”——热评
class Solution {
public Node connect(Node root) {
// 3.深度优先搜索——迭代;先将中间的联合
dfs(root);
return root;
}
void dfs(Node root) {
if(root==null) {
return;
}
Node left = root.left;
Node right = root.right;
//配合动画演示理解这段,以root为起点,将整个纵深这段串联起来
while(left!=null) {
left.next = right;
left = left.right;
right = right.left;
}
//递归的调用左右节点,完成同样的纵深串联
dfs(root.left);
dfs(root.right);
}
}