没看答案,先中序遍历不平衡的BST,再重新构造平衡BST。
# 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 balanceBST(self, root: TreeNode) -> TreeNode:
# 中序遍历BST得到的是递增数组
tree_list = []
def dfs(root):
if not root:
return
dfs(root.left)
tree_list.append(root.val)
dfs(root.right)
dfs(root)
# 重构BST
BST = TreeNode(0)
def rebuildBST(tree_list, BST):
if not tree_list:
return None
mid = len(tree_list) // 2
BST = TreeNode(tree_list[mid])
BST.left = rebuildBST(tree_list[:mid], BST.left)
BST.right = rebuildBST(tree_list[mid+1:], BST.right)
return BST
return rebuildBST(tree_list, BST)
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)