Leetcode: Populating Next Right Pointers in Each Node II

Question

Follow up for problem “Populating Next Right Pointers in Each Node”.

What if the given tree could be any binary tree? Would your previous solution still work?

Note:

You may only use constant extra space.
For example,
Given the following binary tree,
1
/ \
2 3
/ \ \
4 5 7
After calling your function, the tree should look like:
1 -> NULL
/ \
2 -> 3 -> NULL
/ \ \
4-> 5 -> 7 -> NULL
Hide Tags Tree Depth-first Search
Hide Similar Problems (M) Populating Next Right Pointers in Each Node

Solution

The immediate state is that all nodes of several first levels are processed. We are ready to process the next level. The first thing is to traverse all node in current level, so that we can get all children nodes in the next level. Curhead is needed to make sure we find the header pointer for the next level. The ending condition is that lastcur is None.

So we maintain two headpointers, lasthead and curhead, and two pointers for traversing two levels.

# 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

        lasthead, curhead, lastcur, cur = head, None, None, None

        while lasthead!=None:         # begin to do in current line
            lastcur = lasthead

            while lastcur!=None:      # travese all nodes in this level
                if lastcur.left!=None:                 # check whether we have gotten first node in the next level
                    if curhead==None:
                        curhead = lastcur.left
                        pre = curhead
                    else:
                        pre.next = lastcur.left
                        pre = pre.next

                if lastcur.right!=None:
                    if curhead==None:
                        curhead = lastcur.right
                        pre = curhead
                    else:
                        pre.next = lastcur.right
                        pre = pre.next

                lastcur = lastcur.next

            lasthead = curhead        # update lasthead
            curhead = None            # in order to compare in the next while loop

Another brief Solution

brief solution

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