[Leetcode] 1382. Balance a Binary Search Tree

方法1

step1: get in-order traversal
step2: use dfs to convert in-order traversal to BST

time complexity: O(n)
sapce complexity: O(n)

class Solution:
    def balanceBST(self, root: TreeNode) -> TreeNode:
        in_order = []
        self.traverse(root, in_order)
        print(in_order)
        return self.dfs(in_order)
    
    def traverse(self, root, in_order):
        if not root:
            return
        self.traverse(root.left, in_order)
        in_order.append(root.val)
        self.traverse(root.right, in_order)
        
    def dfs(self, vals):
        if not vals:
            return None
        if len(vals) == 1:
            return TreeNode(vals[0])
        mid = len(vals) // 2
        root = TreeNode(vals[mid])
        left = self.dfs(vals[0:mid])
        right = self.dfs(vals[mid + 1:])
        root.left = left
        root.right = right
        return root

你可能感兴趣的:(algorithm,dfs,leetcode,二叉树)