114. 二叉树展开为链表

给定一个二叉树,原地将它展开为一个单链表。

例如,给定二叉树

114. 二叉树展开为链表_第1张图片

将其展开为:

114. 二叉树展开为链表_第2张图片

# Definition for a binary tree node.
# 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 root == None:
            return root
        # 如果左子树为空,右子树非空,递归整理右子树
        if root.left == None and root.right != None:
            self.flatten(root.right)
        # 如果左子树非空,右子树为空,把左子树挪到右子树,递归整理右子树
        elif root.left != None and root.right == None:
            root.right = root.left
            root.left = None
            self.flatten(root.right)
        # 如果左子树右子树都非空,把右子树插到左子树的右下角,把左子树挪到右子树
        elif root.left != None and root.right != None:
            p = root.left
            while p.right != None:
                p = p.right
            p.right = root.right
            root.right = root.left
            root.left = None
            self.flatten(root.right)

你可能感兴趣的:(Leetcode每日一题打卡,leetcode,python,算法)