LeetCode Find Bottom Left Tree Value [Medium]

原题地址

题目内容

这里写图片描述

题目分析

题目的意思为:找到整棵树最后一行最左边的那个数。采用先序遍历的方法,用maxdepth来记录当前最深的的层数,res来记录当前最左的数值。depth来记录当前遍历所在的层数。这里要注意一点的就是判断条件是depth>maxdepth而不是depth>=maxdepth。因为先序遍历是先遍历左子树,所以res肯定是记录leftmost,而如果depth>=maxdepth的话,结果就有可能会变成记录到leftmost的兄弟了,比如在example1中输出的结果就会为3而不是1.

代码实现

/**
 * 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:
    void findleftval(struct TreeNode* root, int depth, int& res, int& maxdepth){
        if(root == NULL){
            return;
        }
        findleftval(root->left,depth+1,res,maxdepth);
        findleftval(root->right, depth+1,res,maxdepth);

        if(depth > maxdepth){
            maxdepth = depth;
            res = root->val;
        }
    }

    int findBottomLeftValue(TreeNode* root) {
        int maxdepth = 0;
        int res = root->val;
        findleftval(root,0,res,maxdepth);
        return res;
    }

};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值