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

Convert Sorted Array to Binary Search Tree -- leetcode

时间:2015-05-08 18:14:35      阅读:111      评论:0      收藏:0      [点我收藏+]

标签:二叉树   leetcode   

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


基本思路:

由于队列已经进行排序,每次取其中点,作为树的根。

即可建得一棵平衡二叉树。


/**
 * 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* sortedArrayToBST(vector<int>& nums) {
        return buildTree(nums, 0, nums.size());
    }
    
    TreeNode *buildTree(vector<int> &nums, int start, int stop) {
        if (start >= stop) return 0;
        int mid = start + (stop-start) / 2;
        TreeNode *root = new TreeNode(nums[mid]);
        root->left = buildTree(nums, start, mid);
        root->right = buildTree(nums, mid+1, stop);
        return root;
    }
};


Convert Sorted Array to Binary Search Tree -- leetcode

标签:二叉树   leetcode   

原文地址:http://blog.csdn.net/elton_xiao/article/details/45582143

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