当前位置:网站首页>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);
边栏推荐
猜你喜欢
随机推荐
使用 Neuron 接入 Modbus TCP 及 Modbus RTU 协议设备
C#中Config文件中,密码的 特殊符号的书写方法。
LeetCode二叉树系列——94.二叉树的中序遍历
虚幻引擎图文笔记:could not be compiled. Try rebuilding from source manually.问题的解决
详解JVM垃圾回收
仿牛客网项目第一章:开发社区首页(详细步骤和思路)
els 方块停在方块上。
leetcode 剑指 Offer 10- I. 斐波那契数列
(文字)无框按钮设置
快解析结合泛微OA
百度推广助手遇到重复关键字,验证错误,怎么一键删除多余的
Re18: Read the paper GCI Everything Has a Cause: Leveraging Causal Inference in Legal Text Analysis
Only after such a stage of development can digital retail have a new evolution
HR团队如何提升效率?人力资源RPA给你答案
一文理解分布式开发中的服务治理
shell脚本
(BUG记录)No module named PIL
学习笔记11--局部轨迹直接构造法
MySQL之COUNT性能到底如何?
Day113.尚医通:微信登录二维码、登录回调接口









