letecode [108] - Convert Sorted Array to Binary Search Tree
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
/ \
-3 9
/ /
-10 5
题目大意:
给定升序排序的数组,将其转换为一个平衡搜索二叉树。
理 解:
根据搜索二叉树的定义,该数组为二叉树的中序遍历结果。又该二叉树为平衡二叉树。输出可能二叉树结果。
用递归的思想,以数组中间的值为根节点,左右序列又可看作左右子树的数组,递归至叶节点。
从而构建二叉树,同时,也保证了构建的二叉树既是平衡二叉树又是搜索二叉树。
代 码 C++:
/** * 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* AnSortedArrayToBST(vector<int>& nums,int left,int right) { if(left > right) return NULL; int mid = (right-left)/2+left; TreeNode* node = new TreeNode(nums[mid]); node->left = AnSortedArrayToBST(nums,left,mid-1); node->right = AnSortedArrayToBST(nums,mid+1,right); return node; } TreeNode* sortedArrayToBST(vector<int>& nums) { int n = nums.size(); if(n==0) return NULL; return AnSortedArrayToBST(nums,0,n-1); } };
运行结果:
执行用时 : 28 ms 内存消耗 : 21.2 MB