首页 > 代码库 > [leetcode]Populating Next Right Pointers in Each Node @ Python

[leetcode]Populating Next Right Pointers in Each Node @ Python

原题地址:https://oj.leetcode.com/problems/populating-next-right-pointers-in-each-node/

题意:

         1
       /        2    3
     / \  /     4  5  6  7
变为:
         1 -> NULL
       /        2 -> 3 -> NULL
     / \  /     4->5->6->7 -> NULL

解题思路:看到二叉树我们就想到需要使用递归的思路了。直接贴代码吧,思路不难。

代码:

# Definition for a  binary tree node
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
#         self.next = None

class Solution:
    # @param root, a tree node
    # @return nothing
    def connect(self, root):
        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)