Given a binary tree
struct TreeLinkNode { TreeLinkNode *left; TreeLinkNode *right; TreeLinkNode *next; }
Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL
.
Initially, all next pointers are set to NULL
.
Solution: Dynamic programming
public class Solution {
public void connect(TreeLinkNode root) {
if(root == null) return;
root.next = null;
subConnect(root);
}
public void subConnect(TreeLinkNode node){
if(node == null || node.left == null || node.right == null) return;
if(node.next == null){
node.left.next = node.right;
node.right.next = null;
}else{
node.left.next = node.right;
node.right.next = node.next.left;
}
subConnect(node.left);
subConnect(node.right);
}
}