RT
思路
a height balanced BST
BST的中序遍歷是一個sorted-array,再構造回去成一個BST,先將中間的元素作為根節點,這個節點的左右分別是左子樹和右子樹。如此遞迴地進行即可。
Solution 1
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode *sortedArrayToBST(vector<int> &num) {
if (num.size() == 0){
return nullptr;
}
TreeNode* root = new TreeNode(0);
sortedArray2BST(num, root); //不被初始化的指標不能用來賦值,編譯不通過
return root;
}
void sortedArray2BST(vector<int> &num, TreeNode* node){
//cout<<num.size()<<endl;
int mid = num.size() / 2;
int val = num[mid];
vector<int>::iterator it_begin = num.begin();
vector<int>::iterator it_end = num.end();
node->val = val;
//cout<<"val:"<<val<<endl;
if (mid > 0){ //防止切分之後的vec為空
vector<int> left_vec(it_begin, it_begin + mid); //attention the index
node->left = new TreeNode(0);
sortedArray2BST(left_vec, node->left);
}
if (mid != num.size() - 1){ //防止切分之後的vec為空
vector<int> right_vec(it_begin + mid+1, it_end); //attention the index
node->right = new TreeNode(0);
sortedArray2BST(right_vec, node->right);
}
}
~Solution(){
//delete the tree nodes
}
};