Leetcode: Populating Next Right Pointers in Each Node

Question

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
Show Tags
Show Similar Problems

Analysis

People are apt to use level traversal which will have to create a queue in O(n) space complexity. However, in this problem, if we have connected two neighbor nodes at the current level, connecting two nodes in the next level is cinch.

Given this knowledge, we only should have three pointers ( Others use two, I haven’t figured it out. ). Two points, p1 and p2, are at the start node of current and the next level, respectively. p1 will traverse to each node in that level. Additional pointer p22 will traverse the nodes at the level with the starter node p2.

Solution

Pass at the first time

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

class Solution(object):
    def connect(self, root):
        """ :type root: TreeLinkNode :rtype: nothing """

        if root==None:
            return 

        root.next = None
        if root.left==None:
            return 

        p1,p2 = root, root.left
        while p2!=None:
            p22 = p2 
            p22.next = p1.right
            p22 = p22.next
            p1 = p1.next
            while p1!=None:
                p22.next = p1.left
                p22 = p22.next
                p22.next = p1.right
                p22 = p22.next
                p1 = p1.next
            p22.next = None

            p1 = p2 
            p2 = p2.left 

你可能感兴趣的:(Leetcode: Populating Next Right Pointers in Each Node)