标签:
Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
把有序数组转化成平衡的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) { if(nums.empty())return NULL; return BuildTree(nums,0,nums.size()-1); } TreeNode* BuildTree(vector<int>& nums,int first,int end) { if(first>end)return NULL; if(first==end)return new TreeNode(nums[first]); int mid=(first+end)/2; TreeNode* root=new TreeNode(nums[mid]); root->left=BuildTree(nums,first,mid-1); root->right=BuildTree(nums,mid+1,end); return root; } };
leetcode No108. Convert Sorted Array to Binary Search Tree
标签:
原文地址:http://blog.csdn.net/u011391629/article/details/52296858