(树)根据排序数组或者排序链表重新构建BST树
2024-09-27 15:41:54
- 题目一:给定一个数组,升序数组,将他构建成一个BST
- 思路:升序数组,这就类似于中序遍历二叉树得出的数组,那么根节点就是在数组中间位置,找到中间位置构建根节点,然后中间位置的左右两侧是根节点的左右子树,递归的对左右子树进行处理,得出一颗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.size()-, num);
}
TreeNode *sortedArrayToBST(int left, int right, vector<int> &num){
if (left > right)
return NULL;
int mid = (left + right)/ + (left + right)% ;
TreeNode *root = new TreeNode(num[mid]);
root->left = sortedArrayToBST(left, mid-, num);
root->right = sortedArrayToBST(mid+, right, num);
return root;
}
}; - 题目二:和第一题类似,只不过数组变成了链表。
- 代码:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
/**
* 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 *sortedListToBST(ListNode *head) {
vector<int> num;
if (head == NULL)
return NULL;
while (head){
num.push_back(head->val);
head = head->next;
}
return sortListToBST(, num.size()-, num);
}
TreeNode *sortListToBST(int start, int end, vector<int> &num){
if (start > end)
return NULL;
int mid = (end + start)/ + (end + start)%;
TreeNode *root = new TreeNode(num[mid]);
root->left = sortListToBST(start, mid-, num);
root->right = sortListToBST(mid+, end, num);
return root;
}
};
最新文章
- Android真机调试 Android.Util.AndroidRuntimeException: You cannot combine custom titles with other title features
- linux 的终端字体色和背景色的修改方法(二)
- 杨辉三角 &;&; 鸽兔同校
- Java 第一天
- 基于Socket的UDP发包程序
- [Objective-c 基础 - 1.1] OC类
- 数据持久层(三)ODB介绍
- spring依赖注入源码分析和mongodb自带连接本地mongodb服务逻辑分析
- 熟悉java堆内存和栈内存和mysql的insert语句中含有id的处理
- java平台的常用资源
- hdu4597 Play Game 区间DP
- ●BZOJ 2149 拆迁队
- DirectX11 With Windows SDK--21 鼠标拾取
- 解决Kettle与Kerberos集成问题
- (转)Spring Boot (十四): Spring Boot 整合 Shiro-登录认证和权限管理
- 课程一(Neural Networks and Deep Learning),第三周(Shallow neural networks)—— 0、学习目标
- python字典获取最大值的键的值
- struts2设置加载非默认路径的struts.xml文件解决方案
- Android客户端面试题集锦
- ADO.NET主要组件
热门文章
- MySQL中的交并差
- split的用法回顾,快忘记了@ →@
- 分表分库之二:唯一ID的生成方法
- 理解contextmanager
- CentOS7 日期时间设置
- 执行make出现“Warning: File `xxx.c' has modification time 2.6e+04 s in the future“警告的解决方法
- VS配置附加包含目录技巧
- Python 正则表达式之选择
- NetBeans+Xdebug调试原理
- div+css显示两行或三行文字