513. 找树左下角的值
https://leetcode.cn/problems/find-bottom-left-tree-value/
https://www.bilibili.com/video/BV1424y1Z7pn/?vd_source=dcd5888def27a31f413605366083456f
给定一个二叉树的 根节点 root
,请找出该二叉树的 最底层 最左边 节点的值。
假设二叉树中至少有一个节点。
示例 1:
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-uVbQTbF9-1670077826097)(%E4%BB%A3%E7%A0%81%E9%9A%8F%E6%83%B3%E5%BD%95%E5%AD%A6%E4%B9%A0.assets/tree1.jpg)]
输入: root = [2,1,3]
输出: 1
示例 2:
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-bn8tGiJT-1670077826099)(%E4%BB%A3%E7%A0%81%E9%9A%8F%E6%83%B3%E5%BD%95%E5%AD%A6%E4%B9%A0.assets/tree2.jpg)]
输入: [1,2,3,4,null,5,6,null,null,7]
输出: 7
class Solution {
public:
int maxDepth = INT_MIN;
int result;
void traversal(TreeNode* root, int depth) {
if (root->left == NULL && root->right == NULL) {
if (depth > maxDepth) {
maxDepth = depth;
result = root->val;
}
return;
}
if (root->left) {
depth++;
traversal(root->left, depth);
depth--; // 回溯
}
if (root->right) {
depth++;
traversal(root->right, depth);
depth--; // 回溯
}
return;
}
int findBottomLeftValue(TreeNode* root) {
traversal(root, 0);
return result;
}
};