0
点赞
收藏
分享

微信扫一扫

513. Find Bottom Left Tree Value**

513. Find Bottom Left Tree Value**

​​https://leetcode.com/problems/find-bottom-left-tree-value/​​

题目描述

Given a binary tree, find the leftmost value in the last row of the tree.

Example 1:

Input:

2
/ \
1 3

Output:
1

Example 2:

Input:

1
/ \
2 3
/ / \
4 5 6
/
7

Output:
7

  • Note: You may assume the tree (i.e., the given root node) is not​​NULL​​.

C++ 实现 1

层序遍历, 每一层记录最左边的第一个元素.

class Solution {
public:
int findBottomLeftValue(TreeNode* root) {
queue<TreeNode*> q;
int last = -1;
q.push(root);
while (!q.empty()) {
auto size = q.size();
for (int i = 0; i < size; ++ i) {
auto r = q.front();
q.pop();
if (i == 0) last = r->val;
if (r->left) q.push(r->left);
if (r->right) q.push(r->right);
}
}
return last;
}
};

C++ 实现 2

采用 DFS 来做, 使用 ​​res​​​ 记录最左侧的值, 同时用 ​​max_depth​​​ 来记录当前访问的最大深度, 只有当 ​​depth > max_depth​​​ 才对最大深度以及 ​​res​​ 进行更新. 由于先遍历左子树, 再遍历右子树, 所以:

if (depth > max_depth) {
max_depth = depth;
res = root->val;
}

这段代码会在遇到最深的最左侧的节点时执行, 该节点同一深度的其他节点, 因为深度均等于 ​​max_depth​​​, 所以该代码不会执行, 因此不会修改 ​​res​​ 中的值.

另外注意题目中说明了最少存在一个节点, 所以 ​​res​​ 初始化时设置为根节点的值.

class Solution {
private:
int res, max_depth = 0;
void dfs(TreeNode *root, int depth) {
if (!root) return;
if (depth > max_depth) {
max_depth = depth;
res = root->val;
}
dfs(root->left, depth + 1);
dfs(root->right, depth + 1);
}
public:
int findBottomLeftValue(TreeNode* root) {
res = root->val;
dfs(root, 0);
return res;
}
};

举报

相关推荐

0 条评论