Problem

You are given a perfect binary tree where all leaves are on the same level, and every parent has two children. The binary tree has the following definition:

struct Node {
  int val;
  Node *left;
  Node *right;
  Node *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.

Examples

Example 1:

Input: root = [1,2,3,4,5,6,7]
Output: [1,#,2,3,#,4,5,6,7,#]
Explanation: Given the above perfect binary tree (Figure A), your function should populate each next pointer to point to its next right node, just like in Figure B. The serialized output is in level order as connected by the next pointers, with '#' signifying the end of each level.

Follow up

  • You may only use constant extra space.
  • The recursive approach is fine. You may assume implicit stack space does not count as extra space for this problem.

Solution

Method 1 - BFS OR Level Order Traversal

We are traversing tree level by level using q.size(). Before that we set rightNode as null. Also, we are doing BFS from right to left.

Code

Java
public Node connect(Node root) {
	if(root == null) return null;
	Queue<Node> q = new LinkedList<>();
	q.offer(root);
	while(!q.isEmpty()) {
		Node rightNode = null;
		for(int i = q.size(); i > 0; i--) {
			Node cur = q.poll();
			cur.next = rightNode;
			rightNode = cur;
			if(cur.right != null) {
				q.offer(cur.right);
				q.offer(cur.left);
			}
		}
	}
	return root;        
}

Complexity

  • Time Complexity - O(n)
  • Space Complexity - O(n) (for queue) But this solution uses memory as recursive solution doesnt. So, lets see another solution.

Method 2 - Recursive DFS

To solve follow up question, we need to use recursion and dfs.

Code

Java
public Node connect(Node root) {
	dfs(root, null);        
	return root;
}

private void dfs(Node curr, Node next) {
	if (curr == null) return;
	curr.next = next;
	dfs(curr.left, curr.right);
	dfs(curr.right, curr.next == null ? null : curr.next.left);
}

Without helper function:

public Node connect(Node root) {
	if (root == null || root.left == null || root.right == null) {
		return;
	}

	root.left.next = root.right;
	root.right.next = root.next == null ? null : root.next.left;

	connect(root.left);
	connect(root.right);
	return root;
}