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.
/** * 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) { if(nums.size() == 0) return NULL; int mid = nums[nums.size()/2]; int i = 0; TreeNode* root = new TreeNode(mid); root->left = toBST(nums, 0, nums.size()/2 - 1); root->right = toBST(nums, nums.size()/2+1, nums.size()-1); return root; } TreeNode* toBST(vector & nums, int begin, int end){ if(begin > end) return NULL; int mid = nums[(begin+end)/2]; TreeNode* root = new TreeNode(mid); root->left = toBST(nums, begin, (begin+end)/2 - 1); root->right = toBST(nums, (begin+end)/2+1, end); return root; }};
将一个升序数组建立一个高度平衡的二叉查找树。 如果高度平衡,则根节点一定是中间的数。用递归。