[LeetCode]题解(python):116-Populating Next Right Pointers in Each Node

时间:2021-11-27 02:14:56

题目来源:

  https://leetcode.com/problems/populating-next-right-pointers-in-each-node/


 

题意分析:

  给定一个二叉完全树,将同一层的节点连起来,其中最后一个节点连接到NULL。如

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

 

题目思路:

  由于是完全树。首先,将所有节点的左子树连接到右子树;然后将节点的右子树连接到下一个节点的左节点。


 

代码(python):

  

[LeetCode]题解(python):116-Populating Next Right Pointers in Each Node[LeetCode]题解(python):116-Populating Next Right Pointers in Each Node
 1 # Definition for binary tree with next pointer.
 2 # class TreeLinkNode(object):
 3 #     def __init__(self, x):
 4 #         self.val = x
 5 #         self.left = None
 6 #         self.right = None
 7 #         self.next = None
 8 
 9 class Solution(object):
10     def connect(self, root):
11         """
12         :type root: TreeLinkNode
13         :rtype: nothing
14         """
15         if root == None or root.left == None:
16             return
17         root.left.next = root.right
18         if root.next:
19             root.right.next = root.next.left
20         self.connect(root.left)
21         self.connect(root.right)
22         
View Code