当前位置:网站首页>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);
边栏推荐
猜你喜欢
随机推荐
ospf2双点双向重发布(题2)
Matplotlib--绘图标记
快解析结合泛微OA
leetcode 剑指 Offer 22. 链表中倒数第k个节点
An article to understand service governance in distributed development
Integral Special Notes-Three Formulas for Curve Area Integral
Jetpack Compose 从入门到入门(八)
详解JVM垃圾回收
日志导致线程Block的这些坑,你不得不防
【HMS core】【FAQ】HMS Toolkit典型问题合集1
STM32CubeMX配置生成FreeRTOS项目
一文理解分布式开发中的服务治理
A new generation of free open source terminal tool, so cool
Day113.尚医通:微信登录二维码、登录回调接口
Using IN in MySQL will not go through index analysis and solutions
debian10安装djando
Two solutions for Excel xlsx file not supported
C#中Config文件中,密码的 特殊符号的书写方法。
CSDN21天学习挑战赛
延迟队列MQ









