当前位置: 首页 > news >正文

【LeetCode】105. 从前序与中序遍历序列构造二叉树 106. 从中序与后序遍历序列构造二叉树

105. 从前序与中序遍历序列构造二叉树

这道题也是经典的数据结构题了,有时候面试题也会遇到,已知前序与中序的遍历序列,由前序遍历我们可以知道第一个元素就是根节点,而中序遍历的特点就是根节点的左边全部为左子树,右边全部为右子树,再依次遍历前序序列,分割中序序列,不断结合这两个序列,就可以写代码了。详细说明都在代码中。因为前序是根左右,中序是左根右。

 

算法代码

class Solution {private int preindex;  //成员变量 是遍历前序数组的索引 弄成成员变量比较好public TreeNode buildTree(int[] preorder, int[] inorder) {return buildTreeChild(preorder,inorder,0,inorder.length-1);}public TreeNode buildTreeChild(int[] preorder,int[] inorder,int inleft,int inright){if(inleft>inright) return null;  //说明当前节点无左右子节点了TreeNode root = new TreeNode(preorder[preindex]);int index = find(inorder,preorder[preindex]); //找在中序数组中的索引,用来分组preindex++; root.left = buildTreeChild(preorder,inorder,inleft,index-1); //先递归并返回当前节点的左子节点root.right = buildTreeChild(preorder,inorder,index+1,inright); //后递归并返回当前节点的右子节点return root;  //最后返回当前节点}public static int find(int[] inorder,int key){ //用来找每个根节点在后序数组中的下标,并返回下标int i = 0;while(inorder[i]!=key){i++;}return i;}
}

 

106. 从中序与后序遍历序列构造二叉树

此题与上个题几乎一模一样,区别在于,是已知中序和后序,而后序的特点是最后一个元素,为根节点,故要对后序序列进行从后往前遍历。并且递归返回左右子树的顺序也要发生改变。剩下的就和前一个代码一样了。因为中序是左根右,后序是左右根。

 

算法代码

class Solution {private int postindex;public TreeNode buildTree(int[] inorder, int[] postorder) {postindex = postorder.length-1;  //指向序列最后一个元素,倒序遍历return buildTreeChild(postorder,inorder,0,postorder.length-1);}private TreeNode buildTreeChild(int[] postorder,int[] inorder ,int inleft,int inright){if(inleft>inright) return null;TreeNode root = new TreeNode(postorder[postindex]);int index = find(inorder,postorder[postindex]);postindex--;root.right = buildTreeChild(postorder,inorder,index+1,inright); //这里有区别root.left = buildTreeChild(postorder,inorder,inleft,index-1); //有区别return root;}private static int find(int[] inorder,int key){int i = 0;while(inorder[i] != key){i++;}return i;}
}

 

http://www.lryc.cn/news/110214.html

相关文章:

  • 堆内存和一些检测工具
  • 【JavaScript】元素获取指南
  • uniapp 返回上一页并刷新
  • Java阶段五Day21
  • 2023,谁在引领实时互动进入高清时代?
  • STM32(HAL)串口中断接收
  • word转pdf怎么转?几种常用方法分享
  • 自学(黑客)技术,入门到入狱!
  • js 函数、闭包及函数对象
  • SSM(Vue3+ElementPlus+Axios+SSM前后端分离)--搭建Vue 前端工程[二]
  • Android 之 AudioManager ( 音频管理器 )
  • 2023爱分析·超自动化厂商全景报告|爱分析报告
  • 【C++进阶知识】04 - 函数默认实参、默认初始化、initializer_list
  • C语言笔试训练【第三天】
  • Android SystemServer中Service的创建和启动方式(基于Android13)
  • Meta开源AI音频和音乐生成模型
  • rust怎么解析json数据?
  • STM32 NOR_FLASH 学习
  • 【数据结构|二叉树遍历】递归与非递归实现前序遍历、中序遍历、后序遍历
  • iPhone 8 Plus透明屏有哪些场景化应用?
  • 解决 MySQL 删除数据后,ID 自增不连续问题
  • arcgis--网络分析(理论篇)
  • Linux笔记1(系统状态等)
  • Set-up ESP-AT Environment on Windows using CMD
  • SpringBoot中Redis报错:NOAUTH Authentication required
  • 需求飙升120%!芭比产品火爆出圈,意大利人争相购买!
  • echarts-pie---------3D曲状环形饼图实现!!!
  • 合并两个有序链表(leetcode)
  • CAS之AtomicReference原理解析
  • JS/JQ实现字符串加密成 HEX(十六进制) 字符串