leetcode513找树左下角的值

解法1:BFS

思路就是层序遍历
用队列记住每层的元素,如果每次记住每层的第一个元素
---->https://programmercarl.com/0102.%E4%BA%8C%E5%8F%89%E6%A0%91%E7%9A%84%E5%B1%82%E5%BA%8F%E9%81%8D%E5%8E%86.html#_102-%E4%BA%8C%E5%8F%89%E6%A0%91%E7%9A%84%E5%B1%82%E5%BA%8F%E9%81%8D%E5%8E%86

class Solution {
public:
    int findBottomLeftValue(TreeNode* root) {
        int ans = bfs(root);
        return ans;
    }
    int  bfs(TreeNode* root){
        
        if(!root->left&&!root->right){
            return root->val;
        }
        int ans=0;
        queue<TreeNode*> qt;
        qt.push(root);
        while(!qt.empty()){
            int sz=qt.size();
            for (int i = 0; i < sz; ++i) {
                TreeNode* tn=qt.front();
                qt.pop();
                if (tn){
                    if(i==0){
                        ans=tn->val;
                    }
                    if(tn->left){
                        qt.push(tn->left);
                    }
                    if(tn->right){
                        qt.push(tn->right);
                    }

                }
            }
        }
        return ans;
    }
};

解法2:DFS

往左边dfs比右边dfs先完成,如果是同一层的话,左边先得到结果
如果结果不是在同一层,那就是深度更深的先得到结果


class Solution {
public:
    int findBottomLeftValue(TreeNode* root) {
        int ans = 0,h=0,curh=0,curVal=-9999999;
        dfs(root,0,curh,curVal);
        return curVal;
    }
    void dfs(TreeNode* node,int h,int& curh,int& curVal){
        if(!node){
            return;
        }
        h++;
        dfs(node->left,h,curh,curVal);
        dfs(node->right,h,curh,curVal);
        if(h>curh){
            curh=h;
            curVal=node->val;
        }
    }
    
};
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

阿维的博客日记

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值