当前位置:网站首页>105. Construct binary tree from preorder and inorder traversal sequence (video explanation!!)
105. Construct binary tree from preorder and inorder traversal sequence (video explanation!!)
2022-07-30 09:54:00 【Learning to pursue high efficiency】
11. (有视频)前序 中序 创建二叉树
Preorder inorder builds the tree
public int preIndex = 0;
private TreeNode buildTreeChild(int[] preorder,int[] inorder,int inbegin,int inend) {
//There is no left tree 或者 There is no right tree
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. 递归函数的参数
- 前序遍历数组,后序遍历数组
- 后序遍历的 Demarcation corner marker
2. The effect of each recursion:创建当前节点(前序)构建左右节点(后序)返回当前节点
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. Build the left tree first,Then build the right tree(pre-order Traverse to the left tree)
root.left = buildTreeChild(preorder,inorder,inbegin,rootIndex-1);
root.right = buildTreeChild(preorder,inorder,rootIndex+1,inend);
边栏推荐
猜你喜欢
随机推荐
Using IN in MySQL will not go through index analysis and solutions
大数据产品:标签体系0-1搭建实践
leetcode 剑指 Offer 21. 调整数组顺序使奇数位于偶数前面
CSDN21天学习挑战赛
A new generation of free open source terminal tool, so cool
20220728 Use the bluetooth on the computer and the bluetooth module HC-05 of Huicheng Technology to pair the bluetooth serial port transmission
Integral Topic Notes - Path Independent Conditions
Access to display the data
2022 Hangzhou Electric Multi-School 2nd Game
快解析结合任我行crm
日志导致线程Block的这些坑,你不得不防
Concise Notes on Integrals - Types of Curve Integrals of the First Kind
MySQL中使用IN 不会走索引分析以及解决办法
An article to understand service governance in distributed development
HCIP --- MPLS VPN实验
els 方块、背景上色
20220728使用电脑上的蓝牙和汇承科技的蓝牙模块HC-05配对蓝牙串口传输
342 · Valley Sequence
初识Apifox——如何使用Apifox做一个简单的接口测试
ThreadLocal内存泄漏是伪命题?









