博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
108.将有序数组转换为二叉搜索树
阅读量:3906 次
发布时间:2019-05-23

本文共 1086 字,大约阅读时间需要 3 分钟。

给你一个整数数组 nums ,其中元素已经按 升序 排列,请你将其转换为一棵 高度平衡 二叉搜索树。

高度平衡 二叉树是一棵满足「每个节点的左右两个子树的高度差的绝对值不超过 1 」的二叉树。
示例
输入:nums = [-10,-3,0,5,9]
输出:[0,-3,9,-10,null,5]
解释:[0,-10,5,null,-3,null,9]
示例
输入:nums = [1,3]
输出:[3,1]
解释:[1,3] 和 [3,1] 都是高度平衡二叉搜索树。

二叉查找树(Binary Search Tree)(又:二叉搜索树,二叉排序树)它或者是一棵空树,或者是具有下列性质的二叉树:

若它的左子树不空,则左子树上所有结点的值均小于它的根结点的值;
若它的右子树不空,则右子树上所有结点的值均大于它的根结点的值;
它的左、右子树也分别为二叉排序树。

而题目要的是:高度平衡二叉搜索树

也就是说左右子树节点数量尽量平衡。

### 代码```c/** * Definition for a binary tree node. * struct TreeNode { *     int val; *     struct TreeNode *left; *     struct TreeNode *right; * }; */struct TreeNode* helper(int* nums, int left, int right) {
if (left > right) {
//边界 return NULL; } // 总是选择中间位置右边的数字作为根节点 int mid = (left + right + 1) / 2; struct TreeNode* root = (struct TreeNode*)malloc(sizeof(struct TreeNode)); root->val = nums[mid]; root->left = helper(nums, left, mid - 1); //左子树递归 root->right = helper(nums, mid + 1, right); // 右子树递归 return root;}struct TreeNode* sortedArrayToBST(int* nums, int numsSize) {
return helper(nums, 0, numsSize - 1);}

转载地址:http://ghqen.baihongyu.com/

你可能感兴趣的文章
dict & set
查看>>
Common Multiple and Least Common Multiple(LCM)
查看>>
大数据处理
查看>>
Difference Between Hard & Soft Links
查看>>
Linux Hard link and Symbolic link
查看>>
redis brief intro
查看>>
mongo db brief intro
查看>>
Kafka basic intro
查看>>
Python multiprocessing
查看>>
Python urlib vs urlib2
查看>>
Python producer & consumer
查看>>
Queue.Queue vs collections.deque
查看>>
Python condition
查看>>
Python Lib Queue.py
查看>>
Producer consumer model
查看>>
count lines in a file - wc & nl
查看>>
需要注意的食物
查看>>
Nginx upstream schedule strategy
查看>>
Redis Brief Intro
查看>>
Nginx Basic Config
查看>>