Find Bottom Left Tree Value(Depth-first-search)
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.
采用深度优先算法(DFS)
基本思想:
搜索节点时,要记录下树的深度,时时更新leftval,比较Dep和dep,确保leftval是最后一排的最左边的值。
/**
* 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 findBottomLeftValue(TreeNode* root) {
int leftval = 0, Dep = -1; //Dep 是整棵树的深度
DFS(root, leftval, Dep, 0);//根节点所处的位置,深度为0
return leftval;
}
private:
void DFS(TreeNode* root, int&leftval, int&Dep, int dep){ //dep是该节点所处的深度
if(dep>Dep){
leftval = root->val;
Dep = dep;
}
if(root->left){//左节点非空
DFS(root->left, leftval, Dep, dep+1);
}
if(root->right){//右节点非空
DFS(root->right, leftval, Dep, dep+1);
}
}
};
test:
Input:
[5,4,7,3,6,2,null,-1,8,9]
Output:
-1