力扣108. 将有序数组转换为二叉搜索树

 

记录一下自己的思路,做完题目后,发现跟答案一模一样。。。记录了个寂寞

题目:【https://leetcode.cn/problems/convert-sorted-array-to-binary-search-tree/description/?envType=study-plan-v2&envId=top-interview-150

 1 /**
 2  * Definition for a binary tree node.
 3  * struct TreeNode {
 4  *     int val;
 5  *     struct TreeNode *left;
 6  *     struct TreeNode *right;
 7  * };
 8  */
 9 
10 struct TreeNode* body(int* arr, int l, int r)
11 {
12     if (l > r)
13         return NULL;
14 
15     int index = (l + r) >> 1;
16 
17     struct TreeNode* t = (struct TreeNode*)malloc(sizeof(struct TreeNode));
18 
19     t->val = arr[index];
20     t->left  = body(arr, l, index - 1);
21     t->right = body(arr, index + 1, r);
22     return t;
23 }
24 
25 struct TreeNode* sortedArrayToBST(int* nums, int numsSize) {
26     return body(nums, 0, numsSize - 1);
27 }

 

posted @ 2025-04-10 15:11  J&YANG  阅读(8)  评论(0)    收藏  举报