码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode] Convert Sorted Array to Binary Search Tree

时间:2015-03-13 18:28:44      阅读:109      评论:0      收藏:0      [点我收藏+]

标签:

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

 

Hide Tags
 Tree Depth-first Search
 
  实现方法有两种,一种是二叉树自下往上 实现,一种是自上往下实现。我用的是后一种方法。
 
#include <iostream>
#include <vector>
using namespace std;
/**
 * Definition for binary tree
 */
struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};

class Solution {
public:
    TreeNode *sortedArrayToBST(vector<int> &num) {
        int n = num.size();
        if(n ==0)   return NULL;
        if(n==1)    return new TreeNode(num[0]);
        return helpFun(num,0,n-1);
    }

    TreeNode * helpFun(vector<int> &num,int lft,int rgt)
    {
        if(lft>rgt) return NULL;
        if(lft==rgt)    return new TreeNode(num[lft]);
        int mid = (lft+rgt)/2;
        TreeNode * curNode = new TreeNode(num[mid]);
        curNode->left = helpFun(num,lft,mid-1);
        curNode->right = helpFun(num,mid+1,rgt);
        return curNode;
    }
};

int main()
{

    return 0;
}

 

[LeetCode] Convert Sorted Array to Binary Search Tree

标签:

原文地址:http://www.cnblogs.com/Azhu/p/4335674.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!