【树】108. 将有序数组转换为二叉搜索树

题目:

【树】108. 将有序数组转换为二叉搜索树

 

 

 

解答:

【树】108. 将有序数组转换为二叉搜索树

 

 

 1 /**
 2  * Definition for a binary tree node.
 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 
13     TreeNode* sortedArrayToBST(vector<int> & num, int start, int end)
14     {
15         if (start > end)
16         {
17             return NULL;
18         }
19 
20         int mid = start + (end - start) / 2;
21         TreeNode *root = new TreeNode(num[mid]);
22         root->left = sortedArrayToBST(num, start, mid - 1);
23         root->right = sortedArrayToBST(num, mid + 1, end);
24 
25         return root;
26     }
27     TreeNode* sortedArrayToBST(vector<int>& nums) 
28     {
29         if (nums.size() <= 0)
30         {
31             return NULL;
32         }
33 
34         return sortedArrayToBST(nums, 0, nums.size() - 1);
35         
36     }
37 };

 

上一篇:108. 分割回文串 II


下一篇:java多线程&&并发面试108问(下)