117-Populating-Next-Right-Pointers-in-Each-Node-II
Previous426-Convert-Binary-Search-Tree-to-Sorted-Doubly-Linked-ListNext99-Recover-Binary-Search-Tree
Last updated
Last updated
/*
// 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) {
if(root==null){
return root;
}
recur(root);
//recur(root);
return root;
}
private void recur(Node root){
if(root==null){
return;
}
//先把当前节点的左右子节点之间的next指针设置好
if(root.left!=null){
if(root.right!=null)
root.left.next=root.right;
else
root.left.next=nextNode(root.next);
}
//再设置当前节点右子节点的next指针
if(root.right!=null){
root.right.next=nextNode(root.next);
}
recur(root.right);
recur(root.left);
}
private Node nextNode(Node root){
while(root!=null){
if(root.left!=null){
return root.left;
}
if(root.right!=null){
return root.right;
}
root=root.next;
}
return null;
}
}