Leetcode: Populating Next Right Pointers in Each Node

Populating Next Right Pointers in Each Node



Similar Problems:


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

Github: code.dennyzhang.com

Credits To: leetcode.com

Leave me comments, if you have better ways to solve.


## Blog link: https://code.dennyzhang.com/populating-next-right-pointers-in-each-node
## Basic Ideas: Process nodes: from top to down, left to right
##              How to process:
##                 p.left.next = p.right
##                 p.right = p.next.left
##              How to move to next node?
##                 p.next
##                 first_node_next_layer: first node of next layer
## Complexity:

# 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:
    def connect(self, root):
        # @param root, a tree link node
        # @return nothing
        if root is None:
            return None
        p = root
        first = p.left
        while p:
            # process p
            if p.left:
                p.left.next = p.right
            if p.right and p.next:
                p.right.next = p.next.left
            # move to next node
            if p.next:
                p = p.next
            else:
                p = first
                if p:
                    first = p.left
                else:
                    first = None
linkedin
github
slack

Share It, If You Like It.

Leave a Reply

Your email address will not be published.