当前位置:网站首页>Leetcode 513. 找树左下角的值
Leetcode 513. 找树左下角的值
2022-06-25 22:03:00 【cwtnice】
原题链接:Leetcode 513. Find Bottom Left Tree Value
Given the root of a binary tree, return the leftmost value in the last row of the tree.
Example 1:
Input: root = [2,1,3]
Output: 1
Example 2:

Input: root = [1,2,3,4,null,5,6,null,null,7]
Output: 7
Constraints:
- The number of nodes in the tree is in the range [1, 104].
- -231 <= Node.val <= 231 - 1
做法一:dfs
思路:
用两个变量记录当前的节点值以及当前节点的最大高度。
每往下一层高度加一,并递归左右子树。(有限递归左子树能保证在同一高度情况下答案一定是最左边的)
如果高度超过了记录的高度,就更新节点值以及最大高度
c++代码:
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */
class Solution {
public:
void dfs(TreeNode* root, int height, int &ans, int &maxHeight){
if(root == nullptr)
return;
// 到下一层, 先递归左孩子, 再递归右孩子
height++;
dfs(root->left, height, ans, maxHeight);
dfs(root->right, height, cuansrVal, maxHeight);
// 当高度比最大高度还大时, 更新
if(height > maxHeight){
ans = root->val;
maxHeight = height;
}
}
int findBottomLeftValue(TreeNode* root) {
// ans为最底层最左边的节点值 maxHeight为最大深度
int ans, maxHeight = 0;
dfs(root, 0, ans, maxHeight);
return ans;
}
};
复杂度分析:
- 时间复杂度:O(n),会遍历每一个节点
- 空间复杂度:O(n),当所有节点都在一边时,递归栈的最大深度就是n
边栏推荐
- UE4 学习记录二 给角色添加骨架,皮肤,及运动动画
- Customize the qcombobox drop-down box, right align the display, and slide the drop-down list
- String object (constant) pool
- Use of xinchida ble 5.0 Low Power Bluetooth module (at command serial port transparent transmission) rsbrs02abr
- 期末复习【机器学习】
- Anaconda一文入门笔记
- 解决‘tuple‘ object has no attribute ‘lower‘
- phoenix索引
- 录屏转gif的好用小工具ScreenToGif,免费又好用!
- Solve 'tuple' object has no attribute 'lower‘
猜你喜欢

Pointer strengthening and improvement

qtcreator 格式化代码

QT Chinese and English use different fonts respectively

konva系列教程2:绘制图形

Leaky API interface practical development series (13): gooseneck cloud service php-api two-dimensional array parameter transfer solution

LeetCode-1528-重新排列字符串-哈希表-字符串

character string

ACM. Hj16 shopping list ●●

Leetcode-1528- rearrange string - hash table - string

Kotlin空指针Bug
随机推荐
二进制、16进制、大端小端
Go language escape analysis complete record
UE4 learning record 2 adding skeleton, skin and motion animation to characters
When are the three tools used for interface testing?
Windows redis installation and simple use
18亿像素火星全景超高清NASA放出,非常震撼
森林的先序和中序遍历
Windows安装Redis及简单使用
Audio basics and PCM to WAV
Style setting when there is a separator in the qcombobox drop-down menu
String对象(常量)池
C. Fibonacci Words-April Fools Day Contest 2021
php性能优化
LeetCode-1528-重新排列字符串-哈希表-字符串
Tree class query component
Qtcreator formatting code
Qt自定义实现的日历控件
My vscode
Xinchida nd04 nd04c nrf52832 (52810) ble module (low power Bluetooth communication module) at command test
213.打家劫舍 II