LeetCode-108.将有序数组转换为二叉搜索树
2021-04-30 13:27
标签:solution 二分查找 lazy log dia www new src node 解题思路: 这道题是要将有序数组转为二叉搜索树,所谓二叉搜索树,是一种始终满足左二分查找法。 C++解法一: 参考自:https://www.cnblogs.com/ariel-dreamland/p/9162481.html LeetCode-108.将有序数组转换为二叉搜索树 标签:solution 二分查找 lazy log dia www new src node 原文地址:https://www.cnblogs.com/luoluosha/p/13228762.html 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(vectorint> &num) {
13 return sortedArrayToBST(num, 0 , num.size() - 1);
14 }
15 TreeNode *sortedArrayToBST(vectorint> &num, int left, int right) {
16 if (left > right) return NULL;
17 int mid = (left + right) / 2;
18 TreeNode *cur = new TreeNode(num[mid]);
19 cur->left = sortedArrayToBST(num, left, mid - 1);
20 cur->right = sortedArrayToBST(num, mid + 1, right);
21 return cur;
22 }
23 };
文章标题:LeetCode-108.将有序数组转换为二叉搜索树
文章链接:http://soscw.com/index.php/essay/80410.html