当前位置:网站首页>力扣今日题513. 找树左下角的值
力扣今日题513. 找树左下角的值
2022-06-23 03:50:00 【抗争的小青年】
513. 找树左下角的值
想法很简单,分别遍历左右子树(前序遍历),到达最大深度时第一次遇到的节点就是最底层最左边的节点。
设置一个变量maxDepth用来记录树的最大深度,再设置一个变量depth来记录当前遍历到的深度,这两个值的初始值都设置为0,设置一个树节点,用来保存结果节点。
在遍历的递归遍历的过程中,如果发现当前遍历的深度depth要大于maxDepth的最大深度,那么就给maxDepth赋值,保证它数据永远在更新,且永远是最大的。同时让res永远指向最深的结点。
class Solution {
//记录树的最大深度
int maxDepth = 0;
//记录traverse 递归遍历到的深度
int depth = 0;
//结果结点,用来保存最底层最左边的结点
TreeNode res = null;
public int findBottomLeftValue(TreeNode root) {
traverse(root);
return res.val;
}
void traverse(TreeNode root){
if(root == null){
return ;
}
//前序遍历的位置
depth++;
if(depth > maxDepth){
//到达最大深度时,第一次遇到的节点就是最底层最左边的结点
maxDepth = depth;
res = root;
}
traverse(root.left);
traverse(root.right);
//后序遍历位置,返回根结点,遍历深度减一
depth--;
}
}
边栏推荐
猜你喜欢

X24cxx series EEPROM chip C language universal reading and writing program

Zhongang Mining: the demand for fluorite in the new energy and new material industry chain has increased greatly

Introduction to deep learning

How MySQL deletes a row of data in a table

Background ribbon animation plug-in ribbon js

Sessions and Daemons

Leetcode 1208. Try to make the strings equal as much as possible (finally solved, good night)

C语言刷题随记 —— 自由落体的球

Cool mouse following animation JS plug-ins 5

Analysis on the current situation of the Internet of things in 2022
随机推荐
VGG 中草药识别
Halcon glue line detection - template matching, pose transformation, glue width, glue continuity detection
【Pytorch】用自动微分求sin(x)的导数
离线数仓建模中常见的概念-术语
[learn FPGA programming from scratch -40]: Advanced - Design - competition and risk
Pta:7-85 data spacing (overload + function template)
反编译
距离度量 —— 余弦距离(Cosine Distance)
TS进阶之infer
3D数学基础[十六] 匀加速直线运动的公式
P1347 sorting (TOPO)
PTA:7-67 友元很简单2016final
[binary tree] flip equivalent binary tree
Lighthouse locally deployed TCA code analysis tool
Cocos学习日记2——脚本和属性
Dynamics 365 插件中权限操作
Prince language on insect date class
How to make the page number start from the specified page in word
How to use shell script to monitor file changes
OpenJudge NOI 1.13 49:计算对数