本文共 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/