Given a binary tree, find the leftmost value in the last row of the tree.
example:
Input:
1
/ \
2 3
/ / \
4 5 6
/
7
Output:
7
这道题是简单的DFS的题目,所以直接放代码:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
int cur_dep, cur_val;
void dfs(TreeNode*root,int depth){
if(root == NULL) return;
else if(cur_dep < depth){
cur_dep = depth;
cur_val = root->val;
}
dfs(root->left,depth+1);
dfs(root->right,depth+1);
}
class Solution {
public:
int findBottomLeftValue(TreeNode* root) {
cur_dep = 0;
cur_val = root->val;
dfs(root,0);
return cur_val;
}
};