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

回溯专题之二叉树

目录

题目链接:

思路分析(全是dfs+递归)+代码实现

二叉树的右视图

思路

代码实现

二叉树展开为链表

思路

代码

路径总和III

思路

代码

二叉树中的最大路径和

思路

代码


最近做了几道二叉树的题,都是力扣hot上面的。都是用dfs+递归的思想解决的。以前学二叉树的时候,觉得递归特别难。但是现在经过回溯的训练后,再看二叉树的递归,是觉得如此之巧妙。跟着我一起暴打力扣hot把,拿下二叉树。

题目链接:

199. 二叉树的右视图 - 力扣(LeetCode)

114. 二叉树展开为链表 - 力扣(LeetCode)

437. 路径总和 III - 力扣(LeetCode)

124. 二叉树中的最大路径和 - 力扣(LeetCode)

思路分析(全是dfs+递归)+代码实现

二叉树的右视图

思路

代码实现
class Solution {List<Integer> ret=new ArrayList<>();int max_deepth=-1;public List<Integer> rightSideView(TreeNode root) {dfs(root,0);return ret;}public void dfs(TreeNode root,int currentdeepth){if(root==null){return;}if(currentdeepth>max_deepth){ret.add(root.val);max_deepth=currentdeepth;}dfs(root.right,currentdeepth+1);dfs(root.left,currentdeepth+1);}
}

二叉树展开为链表

思路

代码
class Solution {List<Integer> ret=new ArrayList<>();public void flatten(TreeNode root) {  pretravle(root);dfs(root,0);}public void pretravle(TreeNode root){if(root==null){return;}ret.add(root.val);pretravle(root.left);pretravle(root.right);}public void dfs(TreeNode root,int pos){if(pos==ret.size()){return;}root.left=null;if(pos+1<ret.size()){root.right=new TreeNode(ret.get(pos+1));dfs(root.right,pos+1);}else{root.right=null;return;}}
}

路径总和III

思路

代码
class Solution {int count=0;int    targetSum=0;public int pathSum(TreeNode root, int _targetSum) {targetSum=_targetSum;travel(root);return count; }public void travel(TreeNode root){
if(root==null){return;}dfs(root,0);travel(root.left);travel(root.right);
}public void dfs(TreeNode root,long currentSum){
if(root==null){return;}currentSum+=root.val;if(targetSum==currentSum){count++;}dfs(root.left,currentSum);dfs(root.right,currentSum);}
}

二叉树中的最大路径和

思路

代码
class Solution {int max=-0x3f3f3f3f;public int maxPathSum(TreeNode root) {//每次进来重置maxmax=-0x3f3f3f3f;dfs(root);return max;  }public int dfs(TreeNode root){if(root==null){return 0;}//如果左子树的和为负数 就直接不选int leftSum=Math.max(0,dfs(root.left));int  rightSum=Math.max(0,dfs(root.right));int currentSum=root.val+leftSum+rightSum;max=Math.max(currentSum,max);return root.val+Math.max(leftSum,rightSum);}}

http://www.dtcms.com/a/594361.html

相关文章:

  • 网站建设工具的种类aspnet网站开发实例项目
  • 怎样制造网站图片教程公司网站建设费用 知乎
  • Python 3.6.1 报错 “module ‘enum‘ has no attribute ‘IntFlag‘” 的真正原因与解决办法
  • 建设网站的重要意义wordpress 去除归档链接
  • 官方网站welcome在家办厂小型加工项目
  • 啥前端框架可以做网站首页企业网站建设招标书
  • 有域名一定要买空间做网站河北沙河市规划局或建设局网站
  • git diff 输出空,但 git status 提示 Motified(M)解决办法
  • 超市设计保定官网seo分析
  • 曼朗策划响应式网站建设网站建设 图书
  • 网站建设模板后台网站建设款分录
  • 【第1章>第5节】图像“膨胀”处理的理论分析与MATLAB仿真测试
  • 企业免费网站模板能从源代码黑进网站修改数据吗
  • iis的网站默认端口昌平建设网站
  • 电流互感器准确级的选择和二次负荷校验
  • bat批处理脚本语法记录
  • 检测站营销方案怎样学做企业网站
  • 百日挑战——单词篇(第十八天)
  • 网站建设好如何开通网站开发与客户交流
  • 广州网站搭建多少钱体验营销案例分析
  • 网站建设公司行业描述填什么龙岩seo
  • Clickhouse数据副本和分片
  • 最长回文子序列
  • 数据库知识整理——关系数据库SQL简介
  • 自己做的网站怎样赚钱东兴网站建设
  • 山东网站营销推广费用百度域名解析
  • 2026助力发刊:人工智能电磁超材料专题学习
  • 作者自己建立的网站网站设计外包合同
  • 零基础入门C语言之C语言实现数据结构之顺序表经典算法
  • 织梦配置手机网站怎样用虚拟主机建网站