题目链接
https://leetcode.com/problems/populating-next-right-pointers-in-each-node/
题目原文
题目大意
二叉树的每个节点都包含左子树和右子树,将同一层的子树用链表连接起来
解题思路
递归求解:
1.如果该节点有左子树:1)该节点有右子树 2)该节点没有右子树 递归该节点的左子树
2.如果该节点有右子树:1)该节点的next节点有左子树 2)该节点的next节点没有左子树
代码
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 not root:
return
else:
root.next = None
self.help(root)
def help(self, node):
if node.left:
if node.right:
node.left.next = node.right
else:
node.left.next = None
self.help(node.left)
if node.right:
if node.next and node.next.left:
node.right.next = node.next.left
else:
node.right.next = None
self.help(node.right)