标签:
Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
这道题是要将有序数组转为二叉搜索树,所谓二叉搜索树,是一种始终满足左<根<右的特性,如果将二叉搜索树按中序遍历的话,得到的就是一个有序数组了。那么反过来,我们可以得知,根节点应该是有序数组的中间点,从中间点分开为左右两个有序数组,在分别找出其中间点作为原中间点的左右两个子节点,这不就是是二分查找法的核心思想么。所以这道题考的就是二分查找法,代码如下:
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: TreeNode *sortedArrayToBST(vector<int> &num) { return sortedArrayToBST(num, 0 , num.size() - 1); } TreeNode *sortedArrayToBST(vector<int> &num, int left, int right) { if (left > right) return NULL; int mid = (left + right) / 2; TreeNode *cur = new TreeNode(num[mid]); cur->left = sortedArrayToBST(num, left, mid - 1); cur->right = sortedArrayToBST(num, mid + 1, right); return cur; } };
[LeetCode] Convert Sorted Array to Binary Search Tree 将有序数组转为二叉搜索树
标签:
原文地址:http://www.cnblogs.com/grandyang/p/4295245.html