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.
这个题看起来就像是深度优先,感觉深度优先的题,很多都会让你写个辅助function,这个function要增加一些代表深度的变量level之类的,还可以视情况增加总深度或者头尾节点之类的,其中function中一般会用到递归去遍历。如果遇到求最小最大最深之类的,至少要给一个min/max变量,在适当的时候去和当前比较,该替换就替换,该保留就保留,嗯,大概就是酱紫。哦,递归还要注意停止递归的条件,对于深度优先,一般就是到了最深处停止咯。
/**
* 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 max=0;
int val=0;
int findBottomLeftValue(TreeNode* root) {
function(root,1);
return val;
}
void function(TreeNode* root, int level){
if(!root) return;
if(level>max){
max=level;
val=root->val;
}
function(root->left,level+1);
function(root->right,level+1);
}
};