当前位置:网站首页>105. 从前序与中序遍历序列构造二叉树(视频讲解!!)
105. 从前序与中序遍历序列构造二叉树(视频讲解!!)
2022-07-30 09:15:00 【学习追求高效率】
11. (有视频)前序 中序 创建二叉树
前序中序构建树
public int preIndex = 0;
private TreeNode buildTreeChild(int[] preorder,int[] inorder,int inbegin,int inend) {
//没有了左树 或者 没有了右树
if(inbegin > inend) {
return null;
}
TreeNode root = new TreeNode( preorder[preIndex]);
//找到当前根节点 在中序遍历中的位置
int rootIndex = findInorderIndex(inorder, preorder[preIndex],inbegin,inend);
preIndex++;
root.left = buildTreeChild(preorder,inorder,inbegin,rootIndex-1);
root.right = buildTreeChild(preorder,inorder,rootIndex+1,inend);
return root;
}
private int findInorderIndex(int[] inorder,int val,int inbegin,int inend) {
for(int i = inbegin;i <= inend;i++) {
if(inorder[i] == val) {
return i;
}
}
return -1;
}
public TreeNode buildTree(int[] preorder, int[] inorder) {
return buildTreeChild(preorder,inorder,0,inorder.length-1);
}
1. 递归函数的参数
- 前序遍历数组,后序遍历数组
- 后序遍历的 分界角标
2. 每次递归的作用:创建当前节点(前序)构建左右节点(后序)返回当前节点
TreeNode root = new TreeNode( preorder[preIndex]);
//找到当前根节点 在中序遍历中的位置
int rootIndex = findInorderIndex(inorder, preorder[preIndex],inbegin,inend);
preIndex++;
root.left = buildTreeChild(preorder,inorder,inbegin,rootIndex-1);
root.right = buildTreeChild(preorder,inorder,rootIndex+1,inend);
return root;
3. 先构建左树,后构建右树(前序先 遍历到左树)
root.left = buildTreeChild(preorder,inorder,inbegin,rootIndex-1);
root.right = buildTreeChild(preorder,inorder,rootIndex+1,inend);
边栏推荐
- 统一异常处理导致ResponseBodyAdvice失效
- 2022 Hangzhou Electric Multi-School 2nd Game
- 积分简明笔记-第二类曲线积分的类型
- leetcode 剑指 Offer 63. 股票的最大利润
- How to avoid CMDB becoming a data island?
- XP电源维修fleXPower电源X7-2J2J2P-120018系列详解
- Integral Topic Notes - Path Independent Conditions
- Excel xlsx file not supported两种解决办法【杭州多测师】【杭州多测师_王sir】
- Devops和低代码的故事:螳螂捕蝉,黄雀在后
- Matplotlib--绘图标记
猜你喜欢

快解析结合任我行crm

Unified exception handling causes ResponseBodyAdvice to fail

PyQt5-在窗口上绘制文本

How to avoid CMDB becoming a data island?

怎么在本地电脑上运行dist文件

Circuit analysis: constant current source circuit composed of op amp and triode

HCIP - MPLS VPN experiment

leetcode 剑指 Offer 15. 二进制中1的个数

积分简明笔记-第二类曲线积分的类型

HCIP --- MPLS VPN实验
随机推荐
快解析结合任我行crm
C#中Config文件中,密码的 特殊符号的书写方法。
PyQt5-绘制不同类型的直线
PyQt5-用像素点绘制正弦曲线
Jetpack Compose 从入门到入门(八)
Explain the problem of change exchange in simple terms - the shell of the backpack problem
Integral Special Notes-Three Formulas for Curve Area Integral
图像分析:投影曲线的波峰查找
342 · Valley Sequence
Using IN in MySQL will not go through index analysis and solutions
Apache DolphinScheduler's new generation of distributed workflow task scheduling platform in practice - Part 1
2022杭电多校第二场
leetcode 剑指 Offer 63. 股票的最大利润
Scala
方法的参数传递
leetcode 剑指 Offer 10- I. 斐波那契数列
Concise Notes on Integrals - Types of Curve Integrals of the First Kind
嘉为鲸翼·多云管理平台荣获信通院可信云技术服务最佳实践
实战演练 | 在 MySQL 中计算每日平均日期或时间间隔
Oracle 创建和操作表