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

[leetcode] Convert Sorted Array to Binary Search Tree

时间:2015-05-07 16:23:48      阅读:134      评论:0      收藏:0      [点我收藏+]

标签:

Convert Sorted Array to Binary Search Tree

Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
 
分析: 我们知道,BST可以通过中序遍历生成一个sorted array,所以,我们能够通每次取中位数的方式生成root节点,将原始的这颗二叉树还原。同时,确定了中位数(root节点),左右字串就能够作为左右子树传递给递归传递参数。
思路: 二分递归转换
 
/**
* Definition for a binary tree node.
* struct TreeNode {
*     int val;
*     TreeNode *left;
*     TreeNode *right;
*     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution
{
public:
  TreeNode *createTree(vector<int> &nums, int left, int right)
  {
    if(left > right)
      return NULL;

    int mid = (left + right)/2;
    TreeNode *root = new TreeNode(nums[mid]);
    root->left = createTree(nums, left, mid-1);
    root->right = createTree(nums, mid+1, right);
    
    return root;
  }

  TreeNode *sortedArrayToBST(vector<int> &nums)
  {
    return createTree(nums, 0, nums.size()-1);
  }
};

 

[leetcode] Convert Sorted Array to Binary Search Tree

标签:

原文地址:http://www.cnblogs.com/lxd2502/p/4484923.html

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