[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)

 

 

[leetcode]Populating Next Right Pointers in Each Node @ Python,古老的榕树,5-wow.com

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。