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

【算法第十五天7.29】513.找树左下角的值 112. 路径总和 106.从中序与后序遍历序列构造二叉树

链接力扣513-找树左下角的值

思路

class Solution {public int findBottomLeftValue(TreeNode root) {Queue<TreeNode> queue = new LinkedList<>();queue.offer(root);int res = 0;while(!queue.isEmpty()){int size = queue.size();for(int i = 0; i < size; i++){TreeNode node = queue.poll();if(i == 0) res = node.val;if(node.left != null) queue.offer(node.left);if(node.right != null) queue.offer(node.right);}}return res;}
}

链接力扣112-路径总和

思路

class Solution {public boolean hasPathSum(TreeNode root, int targetSum) {// 用前序遍历if(root == null) return false;if(root.left == null && root.right == null) return targetSum == root.val;// 求两侧分支的路径和return hasPathSum(root.left, targetSum - root.val) || hasPathSum(root.right, targetSum - root.val);}
}

链接力扣106-从中序与后序遍历序列构造二叉树

思路

//  重点是:左闭右开的原则,以及子树长度
class Solution {Map<Integer,Integer> map;public TreeNode buildTree(int[] inorder, int[] postorder) {map = new HashMap<>();for(int i = 0; i < inorder.length; i++){map.put(inorder[i],i);}return 	getRoot(inorder,0,inorder.length,postorder,0,postorder.length);}public TreeNode getRoot(int[] inorder, int inStart,int inEnd,int[] postorder,int postStart,int postEnd){// 参数里的范围都是前闭后开,不是左闭右开,则无法返回树if(inStart >= inEnd || postStart >= postEnd) return null;// 获取中序中的根节点值;int index = map.get(postorder[postEnd - 1]);TreeNode root = new TreeNode(inorder[index]);// 求出左树的长度int lenOfLeft = index - inStart;// 根据左闭右开,来建立左子树、右子树root.left = getRoot(inorder,inStart,index, postorder,postStart,postStart + lenOfLeft);root.right = getRoot(inorder,index + 1, inEnd, postorder,postStart + lenOfLeft,postEnd - 1);// root.right = getRoot(inorder,index + 1, inEnd, postorder,postStart + index,postEnd - 1);return root;}
}
http://www.lryc.cn/news/111552.html

相关文章:

  • Java thymeleaf bug排查记录
  • 互感和励磁电感(激磁电感)的关系
  • stdexcept和exception,两个头文件的区别?
  • openCV图像的读写操作
  • Android平台GB28181设备接入端如何降低资源占用和性能消耗
  • Android Studio安装AI编程助手Github Copilot
  • windows部署springboot项目 jar项目 (带日志监听和开机自起脚本)
  • 【数据结构和算法】排序算法
  • Error: Cannot find module ‘@babel/core’处理
  • K8S系列文章之 自动化运维利器 Fabric
  • flask--->CBV/模板/请求响应/session
  • Go语言基础:运算符、文件操作、接口、Packages、if else、for循环
  • 2308C++学习简单协程文档
  • C++笔记之从数组指针到函数数组指针(使用using name和std::function)
  • 【数据结构】常见的排序算法
  • CentOS 安装 Jenkins
  • 前端如何设置表格边框样式和单元格间距?
  • Ubuntu 22.04安装搜狗输入法
  • 【C++】初阶 --- 内联函数(inline)
  • VGGNet剪枝实战:使用VGGNet训练、稀疏训练、剪枝、微调等,剪枝出只有3M的模型
  • 【iOS】GCD深入学习
  • Webpack开启本地服务器;HMR热模块替换;devServer配置;开发与生成环境的区分与配置
  • opencv 31-图像平滑处理-方框滤波cv2.boxFilter()
  • Kubernetes关于cpu资源分配的设计
  • Flink读取mysql数据库(java)
  • 小程序学习(五):WXSS模板语法
  • 注解 @JsonFormat 与 @DateTimeFormat 的使用
  • Python实现决策树算法:完整源码逐行解析
  • Linux文本三剑客---grep、sed、awk
  • 局域网VoIP网络电话测试