LeetCode --- Convert Sorted Array to Binary Search Tree

题目链接

Problem discription:

Given an array where elements are sorted in ascending order, convert it to a height balanced BST.

Accepted Code:

 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, int start, int end) {
13         if (start > end) {
14             return NULL;
15         } 
16         // if you write " int middle = start + (end - start) >> 1"
17         // instead of the following sentence, you should keep in 
18         // mind that the priority of ">>" is weaker than "+" operator
19         int middle = start + (end - start) / 2;
20         TreeNode *p = new TreeNode(num[middle]);
21         // elements at the left of num[middle] construct
22         // the left child tree of "p" and its right child
23         // tree consists of elements located at the right
24         // of num[middle]...
25         // because the given array is sorted
26         if (start != end) {
27             p->left = sortedArrayToBST(num, start, middle - 1);
28             p->right = sortedArrayToBST(num, middle + 1, end);
29         }
30         return p;
31     }
32     TreeNode *sortedArrayToBST(vector<int> &num) {
33         // call the overload function
34         return sortedArrayToBST(num, 0, num.size() - 1);
35     }
36 };

 

转载于:https://www.cnblogs.com/Stomach-ache/p/3788490.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值