标签:
Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
解题思路:
用一个有序数组,创建一个平衡二叉查找树。
为确保平衡,需要满足两子树的高度差不大于1,可以通过设置左子树结点数等于或者比右子树结点数多1,来实现。
那么每次取数组的中间位置后一个值,作为根结点,数组左边元素的插入左子树,数组右边元素插入右子树,依次类推。
代码:
1 /** 2 * Definition for a binary tree node. 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */ 10 class Solution { 11 public: 12 TreeNode* sortedArrayToBST(vector<int>& nums) { 13 return MakeSubtree(nums, 0, nums.size()-1); 14 } 15 16 TreeNode* MakeSubtree(vector<int>& nums, int start, int end) { 17 if (start > end) 18 return NULL; 19 20 int mid = (start + end + 1) / 2; 21 TreeNode* root = new TreeNode(nums[mid]); 22 root->left = MakeSubtree(nums, start, mid-1); 23 root->right = MakeSubtree(nums, mid+1, end); 24 return root; 25 } 26 };
【Leetcode】【Medium】Convert Sorted Array to Binary Search Tree
标签:
原文地址:http://www.cnblogs.com/huxiao-tee/p/4518684.html