题目描述:
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 every node 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
解题思路:
解这题前,首先要了解什么是二叉搜索树(BST):
- 若任意节点的左子树不空,则左子树上所有结点的值均小于它的根结点的值;
- 若任意节点的右子树不空,则右子树上所有结点的值均大于它的根结点的值;
- 它是一棵空树或它的左右两个子树的高度差的绝对值不超过1,并且左右两个子树都是一棵平衡二叉树
按二叉搜索数的定义,可以发现一个规律:每个节点的数都相当于分割后数组的“中间”数。比如例子中的第一个节点的数0就是数组[-10,-3,0,5,9]的中间数,向下左分支的第一个节点数-3就是数组[-10,-3]的“中间”数,以此类推。
因此,我们可以写出一个递归函数,从数组的“中间”数开始给二叉树赋值,往下遍历。
代码:
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* createBST(vector<int>& nums,int left,int right){ 13 if(left>=right) 14 //数组中没有数,因为mid+1的原因可能会出现大于的情况 15 return NULL; 16 int mid=(right-left)/2+left;//中间数 17 struct TreeNode* cur=(struct TreeNode*)malloc(sizeof(struct TreeNode)); 18 cur->val=nums[mid];//赋值 19 cur->left=createBST(nums,left,mid); 20 cur->right=createBST(nums,mid+1,right); 21 return cur; 22 } 23 TreeNode* sortedArrayToBST(vector<int>& nums) { 24 return createBST(nums,0,nums.size()); 25 //还有一种写法不需要形参left和right,只要分割数组成两个就行,因为基本一样就不写了 26 } 27 };