Leetcode | Convert Sorted Array to Binary Search Tree

3251 단어 Binary search
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 };

좋은 웹페이지 즐겨찾기