Given a perfect binary tree, where each node has two children and all leaves are at the same depth, update each nodes next pointer to point to its immediate right neighbor at the same level. If there is no neighbor, set the next pointer to None. Return the root node after updating all next' pointers. The input is provided as a binary tree with nodes defined as:
class TreeNode:
def __init__(self, value=0, left=None, right=None, next=None):
self.value = value
self.left = left
self.right = right
self.next = next
The function must update the tree in-place and return the root node.
Example 1
Input: TreeNode(10, TreeNode(5, TreeNode(2), TreeNode(7)), TreeNode(15, TreeNode(12), TreeNode(20)))
Output: TreeNode(10, TreeNode(5, TreeNode(2), TreeNode(7)), TreeNode(15, TreeNode(12), TreeNode(20)))
Explanation: After connecting, each nodes next' pointer points to its immediate right neighbor at the same level, or None if there is no neighbor.
Example 2
Input: None
Output: None
Explanation: Empty tree returns None.
Constraints
Case 1
Input: TreeNode(1, TreeNode(2, TreeNode(4), TreeNode(5)), TreeNode(3, TreeNode(6), TreeNode(7)))
Expected: TreeNode(1, TreeNode(2, TreeNode(4), TreeNode(5)), TreeNode(3, TreeNode(6), TreeNode(7)))
Case 2
Input: TreeNode(8, TreeNode(4, TreeNode(2), TreeNode(6)), TreeNode(12, TreeNode(10), TreeNode(14)))
Expected: TreeNode(8, TreeNode(4, TreeNode(2), TreeNode(6)), TreeNode(12, TreeNode(10), TreeNode(14)))