Teaching Kids Programming – Populating Next Right Pointers in Each Node (Breadth First Search Algorithm)


Teaching Kids Programming: Videos on Data Structures and Algorithms

Given a binary tree:

1
2
3
4
5
6
struct Node {
  int val;
  Node *left;
  Node *right;
  Node *next;
}
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.

binary-tree-next-pointer Teaching Kids Programming - Populating Next Right Pointers in Each Node (Breadth First Search Algorithm) algorithms BFS python teaching kids programming youtube video

binary-tree-next-pointer

Example 1:
Input: root = [1,2,3,4,5,null,7]
Output: [1,#,2,3,#,4,5,7,#]
Explanation: Given the above 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.

Example 2:
Input: root = []
Output: []

Constraints:
The number of nodes in the tree is in the range [0, 6000].
-100 <= Node.val <= 100

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.

Populating Next Right Pointers in Each Node (Breadth First Search Algorithm)

Let’s traverse the binary tree level by level (aka Breadth First Search) and ensure at any time all the nodes in the queue are located in the same level. Thus we can link the Next pointer for any node to its neighbour on the right.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
"""
# Definition for a Node.
class Node:
    def __init__(self, val: int = 0, left: 'Node' = None, right: 'Node' = None, next: 'Node' = None):
        self.val = val
        self.left = left
        self.right = right
        self.next = next
"""
class Solution:
    def connect(self, root: Optional['Node']) -> Optional['Node']:
        if not root:
            return root
        q = deque([root])
        while q:
            n = len(q)
            for i in range(n):
                cur = q.popleft()
                if cur.left:
                    q.append(cur.left)
                if cur.right:
                    q.append(cur.right)
                if i != n - 1:
                    cur.next = q[0]
        return root        
"""
# Definition for a Node.
class Node:
    def __init__(self, val: int = 0, left: 'Node' = None, right: 'Node' = None, next: 'Node' = None):
        self.val = val
        self.left = left
        self.right = right
        self.next = next
"""
class Solution:
    def connect(self, root: Optional['Node']) -> Optional['Node']:
        if not root:
            return root
        q = deque([root])
        while q:
            n = len(q)
            for i in range(n):
                cur = q.popleft()
                if cur.left:
                    q.append(cur.left)
                if cur.right:
                    q.append(cur.right)
                if i != n - 1:
                    cur.next = q[0]
        return root        

We use the deque (double-ended queue) to implement a BFS. The time complexity is O(N) where N is the number of the nodes in the given binary tree. The space complexity is O(N) as we need a queue to store the nodes.

–EOF (The Ultimate Computing & Technology Blog) —

GD Star Rating
loading...
518 words
Last Post: Teaching Kids Programming - Find Combination Sum via Breadth First Search Algorithm
Next Post: Teaching Kids Programming - Algorithms to Check If Any Intervals Overlapping (Meeting Rooms)

The Permanent URL is: Teaching Kids Programming – Populating Next Right Pointers in Each Node (Breadth First Search Algorithm)

Leave a Reply