剑指 Offer(专项突击版)- 剑指 Offer II 052. 展平二叉搜索树(20220729)

给你一棵二叉搜索树,请 按中序遍历 将其重新排列为一棵递增顺序搜索树,使树中最左边的节点成为树的根节点,并且每个节点没有左子节点,只有一个右子节点。

 

示例 1:



输入:root = [5,3,6,2,4,null,8,1,null,null,null,7,9]
输出:[1,null,2,null,3,null,4,null,5,null,6,null,7,null,8,null,9]
示例 2:



输入:root = [5,1,7]
输出:[1,null,5,null,7]


# 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 increasingBST(self, root: TreeNode) -> TreeNode:
        res = []
        def dfs(node):
            if node:
                dfs(node.left)
                res.append(node.val)
                dfs(node.right)

        dfs(root)
        resTree = TreeNode(0)
        cur = resTree
        for item in res:
            cur.right = TreeNode(item)
            cur = cur.right

        return resTree.right

你可能感兴趣的:(2022刷题-目标400+,深度优先,算法,leetcode)