- Leetcode 513. Find Bottom Left T
- LeetCode 513. Find Bottom Left T
- [LeetCode]513. Find Bottom Left
- LeetCode笔记:513. Find Bottom Left
- 力扣每日一题:513.找树左下角的值 Python DFS 、B
- [刷题防痴呆] 0513 - 找树左下角的值 (Find Bot
- 2022-06-22 「513. 找树左下角的值」
- 513. Find Bottom Left Tree Value
- 513. Find Bottom Left Tree Value
- 513. Find Bottom Left Tree Value
原题地址:https://leetcode.com/problems/find-bottom-left-tree-value/description/
题目描述
Given a binary tree, find the leftmost value in the last row of the tree.
即找到一棵树最底层最左边的值返回。
解题思路
一开始是误认为树除了叶子层以外都是满的,所以只想着中序遍历存到vector里最后计算出下标取出目标值,但是发现每一层不都是满的,所以想用双重循环写个深度优先遍历,外重循环每一重对应一层,内重循环对应每一层里的各个节点,然而似乎会超时。
所以我最后的做法是进行深度优先遍历,深度优先遍历函数有个参数记录当前的深度。设一个变量deepest_first
,记录已经访问到的最大深度,如果深度优先遍历的当前深度大于这个最大深度,就更新最大深度的值,并取出当前节点的值。因为深度优先遍历里是先递归左子节点,再递归右子节点,所以这样执行到最后得到的就是最深处最左的节点值。
代码
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int first_deepest=0;
int target = 0;
void DFS(TreeNode* root,int current_level){
if(root==NULL){
return ;
}
current_level+=1;
if(current_level>first_deepest){
first_deepest = current_level;
target = root->val;
}
DFS(root->left,current_level);
DFS(root->right,current_level);
}
int findBottomLeftValue(TreeNode* root) {
DFS(root,0);
return target;
}
};
网友评论