欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

填充每个节点的下一个右侧节点指针-二叉树116-python

程序员文章站 2022-02-28 06:19:34
...

算法思想:

python

# Definition for a Node.
class Node:
    def __init__(self, val: int = 0, left: 'Node' = None, right: 'Node' = None, next: 'Node' = None):
        self.val = val
        self.left = left
        self.right = right
        self.next = next


class Solution:
    def connect(self, root: 'Node') -> 'Node':
        if not root:
            return 
        self.connectTwoNode(root.left, root.right)

        return root

    def connectTwoNode(self, node1, node2):
        if not node1 or not node2:
            return 

        node1.next = node2
        self.connectTwoNode(node1.left, node1.right)
        self.connectTwoNode(node2.left, node2.right)
        self.connectTwoNode(node1.right, node2.left)