這是一道關於二元搜尋樹(Binary Search Tree, BST)的問題。題目要求我們將一個不平衡的二元搜尋樹轉換成一個平衡的二元搜尋樹。
主要步驟如下:
具體實現方法:
這種方法可以保證新樹是平衡的,因為我們總是選擇中間元素作為根節點,從而確保左右子樹的高度差不超過1。
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ class Solution { private: vector<int> sorted; void inorder(TreeNode* root) { if (!root) return; inorder(root->left); sorted.push_back(root->val); inorder(root->right); } TreeNode* construct(vector<int>& sorted, int left, int right) { if (left > right) return nullptr; int mid = (left + right) / 2; TreeNode* root = new TreeNode(sorted[mid]); root->left = construct(sorted, left, mid - 1); root->right = construct(sorted, mid + 1, right); return root; } public: TreeNode* balanceBST(TreeNode* root) { inorder(root); return construct(sorted, 0, sorted.size() - 1); } };
or
By clicking below, you agree to our terms of service.
New to HackMD? Sign up