题目:
- 给定一个二叉树的 根节点
root
,请找出该二叉树的 最底层 最左边 节点的值。假设二叉树中至少有一个节点。
示例:
- 输入: r o o t = [ 2 , 1 , 3 ] root = [2,1,3] root=[2,1,3]
- 输出: 1 1 1
解题思路一:(递归)
- 确定递归函数的参数和返回值:
int mDepth = INT_MIN;
int res;
void dfs(TreeNode* cur, int depth)
- 确定终止条件:
if(cur == NULL) return;
- 确定单层递归逻辑: 先序遍历顺序为: 左 − > 中 − > 右 左->中->右 左−>中−>右
if(cur->left) dfs(cur->left, depth + 1);
if(cur->left == NULL && cur->right == NULL){
if(depth > mDepth){
res = cur->val;
mDepth = depth;
}
}
if(cur->right) dfs(cur->right, depth + 1);
C++版整体代码
class Solution {
public:
int mDepth = INT_MIN;
int res;
void dfs(TreeNode* cur, int depth){
if(cur == NULL) return;
if(cur->left) dfs(cur->left, depth + 1);
if(cur->left == NULL && cur->right == NULL){
if(depth > mDepth){
res = cur->val;
mDepth = depth;
}
}
if(cur->right) dfs(cur->right, depth + 1);
}
int findBottomLeftValue(TreeNode* root) {
dfs(root, 0);
return res;
}
};