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

LeetCode:513、找树左下角的值

//递归法
/*** Definition for a binary tree node.* public class TreeNode {*     int val;*     TreeNode left;*     TreeNode right;*     TreeNode() {}*     TreeNode(int val) { this.val = val; }*     TreeNode(int val, TreeNode left, TreeNode right) {*         this.val = val;*         this.left = left;*         this.right = right;*     }* }*/
class Solution {public int result;public int maxdepth=-1;//初始化为-1是因为当只有一个节点也就是只有根节点时,传来的depth=0,0>-1,才会返回正确的左下角的值public void getresult(TreeNode root,int depth){if(root==null)return;if(root.left==null&&root.right==null){if(depth>maxdepth){maxdepth=depth;result=root.val;}}if(root.left!=null){depth++;getresult(root.left,depth);depth--;}if(root.right!=null){depth++;getresult(root.right,depth);depth--;}}public int findBottomLeftValue(TreeNode root) {getresult(root,0);return result;}
}
//迭代法
class Solution {public int findBottomLeftValue(TreeNode root) {Queue<TreeNode> que=new LinkedList<>();int res=0;que.offer(root);while(!que.isEmpty()){int size=que.size();for(int i=0;i<size;i++){TreeNode tmpnode=que.poll();if(i==0)res=tmpnode.val;//保存二叉树最底边第一个元素if(tmpnode.left!=null)que.offer(tmpnode.left);if(tmpnode.right!=null)que.offer(tmpnode.right);}}return res;}
}

513. 找树左下角的值 - 力扣(LeetCode)513. 找树左下角的值 - 给定一个二叉树的 根节点 root,请找出该二叉树的 最底层 最左边 节点的值。假设二叉树中至少有一个节点。 示例 1:[https://assets.leetcode.com/uploads/2020/12/14/tree1.jpg]输入: root = [2,1,3]输出: 1示例 2:[https://assets.leetcode.com/uploads/2020/12/14/tree2.jpg]输入: [1,2,3,4,null,5,6,null,null,7]输出: 7 提示: * 二叉树的节点个数的范围是 [1,104] * -231 <= Node.val <= 231 - 1 https://leetcode.cn/problems/find-bottom-left-tree-value

相关文章:

  • ngx_http_keyval_module动态键值管理
  • Windows DOS下的常用命令 及 HTML
  • HarmonyOS NEXT应用开发-Notification Kit(用户通知服务)notificationManager.getSlot
  • 安卓常用第三方库
  • 【Web/HarmonyOS】采用ArkTS+Web组件开发网页嵌套的全屏应用
  • 养生:通往健康生活的桥梁
  • 养生:开启健康生活的全新篇章
  • 文件上传总结
  • 基于卡尔曼滤波的传感器融合技术的多传感器融合技术(附战场环境模拟可视化代码及应用说明)
  • MATLAB机器人系统工具箱中的loadrobot和importrobot
  • QMK键盘固件中LED锁定指示灯的配置与使用详解(实操部分+拓展)
  • AI 搜索引擎 MindSearch
  • Xubuntu系统详解
  • Java设计模式之适配器模式:从入门到精通
  • 利用散点图探索宇航员特征与太空任务之间的关系
  • TCPIP详解 卷1协议 十 用户数据报协议和IP分片
  • Python语言在地球科学交叉领域中的应用——从数据可视化到常见数据分析方法的使用【实例操作】
  • 本地文件查重管理工具EasyFileCount v3.0.5.1绿色版,支持查找大重复文件+自动分类
  • CentOS部署Collabora Online
  • SSRF相关
  • 对话郑永年:我们谈判也是为世界争公义
  • 夜读丨取稿费的乐趣
  • 中共中央、国务院印发《生态环境保护督察工作条例》
  • 波兰关闭俄罗斯驻克拉科夫领事馆
  • 菲律宾举行中期选举
  • 数说母亲节|全球11亿女性进入更年期,“不是忍忍就好”