首页 > 代码库 > Leetcode:Convert Sorted Array to Binary Search Tree
Leetcode:Convert Sorted Array to Binary Search Tree
Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
分析:对于BST,左右子树的高度差小于等于1,则在由sorted array构建BST时把数组中间元素作为根节点,然后递归的构建左右子树。代码如下:
1 class Solution { 2 public: 3 TreeNode *sortedArrayToBST(vector<int> &num) { 4 return build_BST(num, 0, num.size()-1); 5 } 6 7 TreeNode *build_BST(vector<int> &num, int start, int end){ 8 if(start > end) return NULL; 9 10 int mid = (start + end)/2;11 TreeNode *root = new TreeNode(num[mid]);12 root->left = build_BST(num, start, mid-1);13 root->right = build_BST(num, mid+1, end);14 15 return root;16 }17 };
Leetcode:Convert Sorted Array to Binary Search Tree
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。