Leetcode 116: Populating Next Right Pointers in Each Node

116. Populating Next Right Pointers in Each Node 

  • Total Submissions: 287603
  • Difficulty: Medium
  • Contributors: Admin

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.

Note:

  • You may only use constant extra space.
  • You may assume that it is a perfect binary tree (ie, all leaves are at the same level, and every parent has two children).

For example,
Given the following perfect binary tree,

         1
       /  \
      2    3
     / \  / \
    4  5  6  7

After calling your function, the tree should look like:

         1 -> NULL
       /  \
      2 -> 3 -> NULL
     / \  / \
    4->5->6->7 -> NULL
 

 

Code

# Definition for binary tree with next pointer.
# class TreeLinkNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
#         self.next = None

class Solution:
    # @param root, a tree link node
    # @return nothing
    def connect(self, root):
        if root is None: 
            return
        
        pre = root
        while pre.left:
            pre_bakup = pre

            while pre:
                pre.left.next = pre.right
                if pre.next:
                    pre.right.next = pre.next.left
                pre = pre.next

            pre = pre_bakup.left

 

Idea

You traverse nodes in a zigzag-like path. For every node being visited, you set its left child’s next to right child. If the node itself has next node, then its right child should also point to the node’s next node’s left child.

Below is the traversal path of pre:

zigzag

The idea uses O(1) space and O(N) time, where N is the number of nodes in the binary tree.

Reference: https://discuss.leetcode.com/topic/2202/a-simple-accepted-solution

 

Code (Using BFS, space complexity is O(N))

# Definition for binary tree with next pointer.
# class TreeLinkNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
#         self.next = None

from collections import *

class Solution:
    # @param root, a tree link node
    # @return nothing
    def connect(self, root):
        if root is None:
            return

        q = deque([(root, 0)])
        while q:
            if len(q) > 1:
                # if two nodes have the same level
                if q[0][1] == q[1][1]:
                    q[0][0].next = q[1][0]
            
            n, lvl = q.popleft()
            
            if n.left and n.right:
                q.append((n.left, lvl+1))
                q.append((n.right, lvl+1))            

 

 

Leave a comment

Your email address will not be published. Required fields are marked *