← Home

1382. Balance a Binary Search Tree

LeetCode article · C++ solution
Website made by wuisabel-gif · Original C++ code by keineahnung2345
binary searchC++Markdown
138

This is one of those problems where the clean idea matters more than the amount of code. For 1382. Balance a Binary Search Tree, the solution in this repository is mainly a binary search solution.

Guide

What?

The first job is to translate the English prompt into state, transition, and stopping conditions. Instead of trying to be clever immediately, read the code as a sequence of questions:

  • What state are we keeping?
  • How do we move from one state to the next?
  • When do we know the answer is already determined?

For this file, the main tools are: binary search.

Guide

When?

This is the kind of solution you want when the problem has structure hiding inside a messy-looking input. The accepted code reduces that pressure by storing exactly the information that remains useful later.

The important function names to track are inOrder, buildTree, balanceBST.

Guide

Why?

The point of the implementation is not to make the code longer. It is to avoid doing the same thinking twice.

  • The final return is not magic; it is the invariant after the loops or recursion have finished doing their accounting.

Guide

How?

Walk through the solution in this order:

  1. Start from the smallest reliable state.
  2. Expand one legal move at a time.
  3. Cache, count, or merge information as soon as it becomes settled.
  4. Let the final stored value answer the original question.

The most important competitive-programming habit here is to trust the invariant. Once the invariant is right, the loops become much less scary.

Guide

Complexity

  • Time: O(n) to O(n log n), depending on the dominant loop or data structure operation
  • Space: O(n) in the usual case for auxiliary containers or recursion

Guide

C++ Solution

Your submission

The accepted solution

solution.cpp
01//Runtime: 188 ms
02//Memory Usage: 52 MB
03/**
04 * Definition for a binary tree node.
05 * struct TreeNode {
06 *     int val;
07 *     TreeNode *left;
08 *     TreeNode *right;
09 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
10 * };
11 */
12class Solution {
13public:
14    void inOrder(TreeNode* node, vector<int>& nums){
15        if(!node)return;
16        inOrder(node->left, nums);
17        nums.push_back(node->val);
18        inOrder(node->right, nums);
19    }
20    
21    TreeNode* buildTree(vector<int>& nums, int start, int end){
22        //end is inclusive
23        if(start > end) return NULL;
24        int mid = (start+end)/2;
25        TreeNode* newroot = new TreeNode(nums[mid]);
26        newroot->left = buildTree(nums, start, mid-1);
27        newroot->right = buildTree(nums, mid+1, end);
28        return newroot;
29    }
30    
31    TreeNode* balanceBST(TreeNode* root) {
32        //parse tree
33        vector<int> nums;
34        inOrder(root, nums);
35        
36        // for(int e : nums){
37        //     cout << e << " ";
38        // }
39        // cout << endl;
40        
41        //build tree
42        int N = nums.size();
43        TreeNode* newroot = new TreeNode(nums[N/2]);
44        newroot->left = buildTree(nums, 0, N/2-1);
45        newroot->right = buildTree(nums, N/2+1, N-1);
46        
47        return newroot;
48    }
49};

Cost

Complexity

Time
O(n) to O(n log n), depending on the dominant loop or data structure operation
Dominated by the main traversal, recursion, or data-structure operations in the code.
Space
O(n) in the usual case for auxiliary containers or recursion
Auxiliary state plus the answer structure where the problem requires one.