首页 > 其他 > 详细

[leetCode]Convert Sorted Array to Binary Search Tree

时间:2014-03-15 06:00:08      阅读:467      评论:0      收藏:0      [点我收藏+]

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

构建平衡二叉排序树(AVL

注意到平衡二叉排序树的根节点是数组的中间点就好,之后是递归。

bubuko.com,布布扣
 1 #include <iostream>
 2 #include <vector>
 3 using namespace std;
 4 
 5 struct TreeNode {
 6     int val;
 7     TreeNode *left;
 8     TreeNode *right;
 9     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
10 };
11 class Solution {
12 public:
13     TreeNode *sortedArrayToBST(vector<int> &num) {
14         TreeNode *head = build(num,0,num.size()-1);
15         return head;
16     }
17     TreeNode *build(vector<int> &num, int low, int high){
18         int headnum = (low+high)/2;
19         if(low > high) return NULL;
20         TreeNode *head = new TreeNode(num[headnum]);
21         head->left = build(num, low,headnum-1);
22         head->right = build(num,headnum+1,high);
23         return head;
24     }
25 };
bubuko.com,布布扣

[leetCode]Convert Sorted Array to Binary Search Tree,布布扣,bubuko.com

[leetCode]Convert Sorted Array to Binary Search Tree

原文:http://www.cnblogs.com/marylins/p/3601273.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!