[Leetcode] convert sorted array to binary search tree

Posted 王大咩的图书馆

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[Leetcode] convert sorted array to binary search tree相关的知识,希望对你有一定的参考价值。

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

题意:将已排序的数组转成高度平衡的搜索二叉树。

思路:这题和Convert sorted list to binary search tree 方法一的处理方法基本一样,不同是数组可以直接访问某个元素,而链表不可以。代码如下:

 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     {
14         if(num.size()==0)   return NULL;
15         return reBulidBST(num,0,num.size()-1);
16     }
17     TreeNode *reBulidBST(vector<int> &num,int beg,int end)
18     {
19         if(beg>end) return NULL;
20 
21         int mid=beg+(end-beg+1)/2;
22         TreeNode *root=new TreeNode(num[mid]);
23         root->left=reBulidBST(num,beg,mid-1);
24         root->right=reBulidBST(num,mid+1,end);
25 
26         return root;
27     }
28 };

以上是关于[Leetcode] convert sorted array to binary search tree的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode 108. Convert Sorted Array to Binary Search Tree

LeetCode OJ 108. Convert Sorted Array to Binary Search Tree DFS求解

Leetcode 108. Convert Sorted Array to Binary Search Tree

[LeetCode]题解(python):108-Convert Sorted Array to Binary Search Tree

LeetCode Convert Sorted List to Binary Search Tree

leetcode-algorithms-109. Convert Sorted List to Binary Search Tree