LeetCode 1382. Balance a Binary Search Tree - solution with TypeScript & JavaScript
ฝัง
- เผยแพร่เมื่อ 25 มิ.ย. 2024
- Daily LeetCode Challenge: Day 113: leetcode.com/problems/balance...
GitHub: github.com/RuslanTsykaliak/Le...
Intuition
When we encounter a binary search tree that is unbalanced, we need to transform it into a balanced one. The key idea is to perform an in-order traversal of the original tree to collect the node values, and then construct a balanced BST using those values.
Approach
In-Order Traversal:
Start at the root.
Recurse on the left subtree.
Record the current node's value.
Recurse on the right subtree.
Repeat until we've visited all nodes.
Recursive Building:
Given an index range [l, r], find the middle index m.
Create a new node with value nums[m].
Recursively build the left subtree with indices [l, m - 1].
Recursively build the right subtree with indices [m + 1, r].
The Result:
Our final answer will be the result of calling build(0, nums.length - 1), where nums contains the collected values.
Hastags: #BalancingBSTs #AlgorithmMagic #CodeExplained #TechJourney #ProblemSolvingSkills #CodingCommunity #LeetCodeSolutions #TrendingTech #LearnToCode #DailyCodingChallenge #Day113 #TechTips #CodeWithMe #CreativeCoding #GeekLife #RuslanTsykaliak