513. 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.
方法1: dfs
思路:
class Solution {
public:
int findBottomLeftValue(TreeNode* root) {
vector<int> res;
dfs(root, 0, res);
return res.back();
}
void dfs(TreeNode* root, int depth, vector<int> & res) {
if (!root) return;
if (depth == res.size()) res.push_back({root -> val});
dfs(root -> left, depth + 1, res);
dfs(root -> right, depth + 1, res);
return;
}
};
class Solution {
public:
int findBottomLeftValue(TreeNode* root) {
int res = -1, depth_mx = -1;
dfs(root, 0, res, depth_mx);
return res;
}
void dfs(TreeNode* root, int depth, int & res, int & depth_mx) {
if (!root) return;
if (depth > depth_mx) {
depth_mx = depth;
res = root -> val;
}
dfs(root -> left, depth + 1, res, depth_mx);
dfs(root -> right, depth + 1, res, depth_mx);
return;
}
};