标签:style class blog code java http
Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
递归,二分法。
1 /** 2 * Definition for binary tree 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */ 10 class Solution { 11 public: 12 TreeNode *sortedArrayToBST(vector<int> &num) { 13 return recursive(num, 0, num.size() - 1); 14 } 15 16 TreeNode *recursive(vector<int> &num, int s, int e) { 17 if (s > e) return NULL; 18 int mid = (s + e) / 2; 19 TreeNode* root = new TreeNode(num[mid]); 20 root->left = recursive(num, s, mid - 1); 21 root->right = recursive(num, mid + 1, e); 22 return root; 23 } 24 };
Leetcode | Convert Sorted Array to Binary Search Tree,布布扣,bubuko.com
Leetcode | Convert Sorted Array to Binary Search Tree
标签:style class blog code java http
原文地址:http://www.cnblogs.com/linyx/p/3784207.html