您的位置:首页 > 其它

leetcode-108-Convert Sorted Array to Binary Search Tree

2017-02-12 20:04 375 查看

问题

题目:[leetcode-108]

思路

本省以为是BST调整为AVL。没有思路,看了下别人给的思路。其实就是根据二分查找的思路去构造BST。一样是AVL。

那么语义就很清晰了。

TreeNode* biInsert(TreeNode* root, const std::vector& nums, int low, int high)

表示把[low, high]区间内的数插入到root中,具体的插入方式遵循BST的插入逻辑。

所以,又写了BST的辅助函数。

代码

/**
* Definition for a binary tree node.
* struct TreeNode {
*     int val;
*     TreeNode *left;
*     TreeNode *right;
*     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* sortedArrayToBST(vector<int>& nums) {
int sz = nums.size();
if(!sz) return NULL;

int low = 0;
int high = sz - 1;

TreeNode* root = NULL;
return biInsert(root, nums, low, high);
}
private:
TreeNode* biInsert(TreeNode* root, const std::vector<int>& nums, int low, int high){
if(low <= high){
int mid = (low+high)/2;
TreeNode* s = new TreeNode(nums[mid]);

root = insertBST(root, s);
biInsert(s, nums, low, mid-1);
biInsert(s, nums, mid + 1,high);

return root;
}
else return NULL;
}
TreeNode* insertBST(TreeNode* root, TreeNode* s){
if(!s) return root;

if(!root) root = s;
else{
if(s->val < root->val) root->left = s;
else root->right = s;
}
return root;
}
};
```c++

<div class="se-preview-section-delimiter"></div>

##代码1
这个语义更加的清晰,就是把区间[low,high]生成一棵BST。

<div class="se-preview-section-delimiter"></div>


/**

* Definition for a binary tree node.

* struct TreeNode {

* int val;

* TreeNode *left;

* TreeNode *right;

* TreeNode(int x) : val(x), left(NULL), right(NULL) {}

* };

*/

class Solution {

public:

TreeNode* sortedArrayToBST(vector& nums) {

int sz = nums.size();

if(!sz) return NULL;

int low = 0;
int high = sz - 1;

return biInsert(nums, low, high);
}


private:

TreeNode* biInsert(const std::vector& nums, int low, int high){

if(low <= high){

int mid = (low+high)/2;

TreeNode* root = new TreeNode(nums[mid]);

root->left = biInsert(nums, low, mid-1);
root->right = biInsert(nums, mid + 1,high);

return root;
}
else return NULL;
}


};

“`
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: