[leetcode] Convert Sorted Array to Binary Search Tree

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);
  }
};

 

posted @ 2015-05-07 14:54  imKirin  阅读(84)  评论(0编辑  收藏  举报