Balance a Binary Search Tree — LeetCode 1382 Python Solution
MediumGreedyTreeDepth-First SearchBinary Search TreeDivide and ConquerBinary Tree
- Problem
- #1382
- Pattern
- Tree Traversal
- Reading time
- 5 min
- Source
- leetcode.com
The problem
Given the root of a binary search tree, return a balanced binary search tree with the same node values. If there is more than one answer, return any of them.
Example
- Input
- root = [1,null,2,null,3,null,4,null,null]
- Output
- [2,1,3,null,null,null,4]
- Explanation
- This is not the only correct answer, [3,1,4,null,2] is also correct.
Python solution
Python
# 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:
def dfs(root: TreeNode):
if root is None:
return
dfs(root.left)
nums.append(root.val)
dfs(root.right)
def build(i: int, j: int) -> TreeNode:
if i > j:
return None
mid = (i + j) >> 1
left = build(i, mid - 1)
right = build(mid + 1, j)
return TreeNode(nums[mid], left, right)
nums = []
dfs(root)
return build(0, len(nums) - 1)Complexity
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(n) auxiliary |
Pattern: Tree Traversal
Choose the order — preorder, inorder, postorder, level — and the problem solves itself. LeetCode 1382. Balance a Binary Search Tree is filed here because LeetCode tags it Tree, Binary Tree and Binary Search Tree, which is the vocabulary this hub collects.
The tree traversal guide has the Python template for the pattern and the 225 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 1382. Balance a Binary Search Tree?
- LeetCode 1382. Balance a Binary Search Tree is rated Medium on LeetCode.
- What is the time complexity of LeetCode 1382. Balance a Binary Search Tree?
- The Python solution on this page runs in O(n).
- What is the space complexity of LeetCode 1382. Balance a Binary Search Tree?
- The Python solution on this page uses O(n) auxiliary space.
- What topics does LeetCode 1382. Balance a Binary Search Tree cover?
- LeetCode 1382. Balance a Binary Search Tree is tagged Greedy, Tree, Depth-First Search, Binary Search Tree, Divide and Conquer and Binary Tree on LeetCode.