当前位置:网站首页>生成二叉搜索平衡树[利用树递归特性]
生成二叉搜索平衡树[利用树递归特性]
2022-06-23 15:13:00 【REN_林森】
前言
对于树而言,就是一个递归结构,也致于处理好任意一颗子树,就处理好了整个树。所以递归结构就只有一个递归体这么简洁。利用树的递归特性,采用从下到上的子树生成+拼接来完成二叉搜索平衡树的生成。
一、有序链表转换二叉搜索树

二、从下到上回溯生成二叉搜索平衡树
package everyday.medium;
import java.util.ArrayList;
import java.util.List;
// 有序链表转换为二叉搜索树
public class SortedListToBST {
/* target:将升序单向链表转化成高度平衡二叉搜索树。 先把链表元素放数组中,便于递归取值。 树还是需要递归生成,而且需要从上往下生成。 */
public TreeNode sortedListToBST(ListNode head) {
// 取单向链表元素。
List<Integer> nums = new ArrayList<>();
while (head != null) {
nums.add(head.val);
head = head.next;
}
// 递归生成树。
return buildTree(nums, 0, nums.size() - 1);
}
private TreeNode buildTree(List<Integer> nums, int begin, int end) {
// 当begin > end时,说明没有可生成节点,那就生成null节点。
if (begin > end) return null;
// 当只有一个元素时,返回叶子节点。
if (begin == end) return new TreeNode(nums.get(begin));
// 递归生成树。
// 加1纯粹是看leetcode例子,当两个值时,选左 + 根。
// 可以不加1,则表示,当两个值时,选根 + 右。
int mid = begin + (end - begin + 1 >>> 1);
TreeNode root = new TreeNode(nums.get(mid));
root.left = buildTree(nums, begin, mid - 1);
root.right = buildTree(nums, mid + 1, end);
// 返回生成好的子树。
return root;
}
// Definition for singly-linked list.
public class ListNode {
int val;
ListNode next;
ListNode() {
}
ListNode(int val) {
this.val = val;
}
ListNode(int val, ListNode next) {
this.val = val;
this.next = next;
}
}
// Definition for a binary tree node.
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode() {
}
TreeNode(int val) {
this.val = val;
}
TreeNode(int val, TreeNode left, TreeNode right) {
this.val = val;
this.left = left;
this.right = right;
}
}
}
总结
1)利用好树的递归特质。
2)从下到上生成并拼装树。
参考文献
边栏推荐
猜你喜欢
随机推荐
Pop() element in JS
嵌入式软件架构设计-程序分层
F5《2022年应用策略现状报告》:边缘部署及负载安全成亚太地区关注焦点
Half wave loss equal thickness and equal inclination interference
golang 重要知识:waitgroup 解析
TCP协议笔记
139. 單詞拆分
Analysis of graphical level-1 programming problem of Electronic Society: cat and mouse
[普通物理] 半波损失 等厚与等倾干涉
Explore the "store" on the cloud. The cloud store is newly upgraded!
云上探“店”,云商店全新升级!
How strong is Jingdong's takeout after entering meituan and starving the hinterland?
5 minutes to quickly launch web applications and APIs (vercel)
xcbdfbs xcvb
Sorting out and summarizing the handling schemes for the three major exceptions of redis cache
Gartner's latest report: development of low code application development platform in China
自监督学习(SSL)Self-Supervised Learning
get_edges
TCP协议三次握手和四次挥手抓包分析
Big factory Architect: how to draw a grand business map?








