【LeetCode & 剑指offer刷题】树题17:Convert Sorted Array to Binary Search Tree

【LeetCode & 剑指offer 刷题笔记】目录(持续更新中...)

Convert Sorted Array to Binary Search Tree

Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of everynode never differ by more than 1.
Example:
Given the sorted array: [-10,-3,0,5,9],
 
One possible answer is: [0,-3,9,-10,null,5], which represents the following height balanced BST:
 
   0
  /  \
 -3   9
 /    /
-10  5

C++
 
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
 
/*
方法:分治法(分成处理左右子序列的问题,与快速排序写法类似)
二叉查找树,根结点总是大于左子树所有结点值,小于右子树所有结点值,中序遍历序列为升序排列
 
分析:转化成一个height-balanced的二叉查找树所以数组中点就是二叉查找树的根结点
写递归思路:先写递归的主体,再写起点输入,再写递归的出口return语句(尤其注意递归的子函数的出口)
*/
class Solution
{
public:
    TreeNode* sortedArrayToBST(vector<int>& nums)
    {
        return buildTree(nums,0,nums.size()-1); //注意索引从0开始
    }
   
    TreeNode* buildTree(vector<int>& nums, int start, int end)
    {
       
        if(start > end) return NULL; //递归子函数的出口(不能取等号,因为单个元素也要分配空间)
       
        int mid = (start + end + 1)/2; //+1是为了向上取整,由于是升序排列,当(start+end)/2不为整数时,取较大的那个数作为根
        TreeNode* root = new TreeNode(nums[mid]);   //构建根结点
        root->left = buildTree(nums, start, mid-1); //构建左子树
        root->right = buildTree(nums, mid+1, end); //构建右子树
       
        return root; //递归原始母函数的出口,返回最顶层的根结点指针
       
    }
};
 

 

posted @ 2019-01-05 19:50  wikiwen  阅读(175)  评论(0编辑  收藏