【LEETCODE】116-Populating Next Right Pointers in Each Node

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


题意:

给一个二叉树,节点如下定义,

# class TreeLinkNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
#         self.next = None

初始状态时,每个节点的next指针都是指向null

要得到的是,每个节点,如果它的右边有节点,就让它的next指向它

如果它的右边没有节点了,就指向null


注意:

只能用常数级额外空间

假设这棵树是完美的,所有叶端点都具有相同的level,每个节点都有两个children


参考:

http://www.cnblogs.com/zuoyuan/p/3745170.html

http://www.cnblogs.com/felixfang/p/3647898.html


思路:

# 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 and root.left:
            root.left.next=root.right
            
            if root.next:
                root.right.next=root.next.left
            else:
                root.right.next=None
            
            self.connect(root.left)
            self.connect(root.right)




你可能感兴趣的:(LeetCode,python)