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

二叉树展开为链表-二叉树114-python

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

算法思想:

python

class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right

class Solution:
    def flatten(self, root: TreeNode) -> None:
        """
        Do not return anything, modify root in-place instead.
        """
        if not root:
            return
        
        self.flatten(root.left)
        self.flatten(root.right)

        left = root.left
        right = root.right

        root.right = left
        root.left = None

        p = root
        while(p.right != None):
            p = p.right
        
        p.right = right