题目链接:https://leetcode.com/problems/populating-next-right-pointers-in-each-node/
思路:
对root节点进行一直向左节点深度遍历,遍历到的每一个节点都是每一层的起始节点。
Example:
外层遍历为1-2-4;
对于1,把1的左节点和右节点连接上;
对于2,把2的左节点和右节点连接上,同时别忘了把2的右节点与3的左节点连接上,否则会断链。
......
方法一:迭代
AC 0ms 100% Java:
/*
// Definition for a Node.
class Node {
public int val;
public Node left;
public Node right;
public Node next;
public Node() {}
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) {
if(root==null)
return null;
Node prev=root;
Node cur=null;
while(prev.left!=null){
cur=prev;
while(cur!=null){
cur.left.next=cur.right;
if(cur.next!=null)
cur.right.next=cur.next.left;
cur=cur.next;
}
prev=prev.left;
}
return root;
}
}
方法二:递归
思路和方法一相同:
AC 0ms 100% Java:
/*
// Definition for a Node.
class Node {
public int val;
public Node left;
public Node right;
public Node next;
public Node() {}
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) {
Node p=root;
helper(p);
return root;
}
public void helper(Node root){
if(root==null)
return;
if(root.left!=null)
root.left.next=root.right;
if(root.right!=null)
root.right.next=root.next==null?null:root.next.left;
helper(root.left);
helper(root.right);
}
}