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;
        }
    }
    
};

相关推荐

  1. leetcode513

    2024-03-18 19:04:01       42 阅读
  2. Leetcode 513

    2024-03-18 19:04:01       31 阅读
  3. 二叉---

    2024-03-18 19:04:01       20 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-03-18 19:04:01       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-03-18 19:04:01       101 阅读
  3. 在Django里面运行非项目文件

    2024-03-18 19:04:01       82 阅读
  4. Python语言-面向对象

    2024-03-18 19:04:01       91 阅读

热门阅读

  1. 【C语言】打印闰年

    2024-03-18 19:04:01       40 阅读
  2. 【工具篇】Unity翻书效果插件Book-Page Curl Pro教程

    2024-03-18 19:04:01       39 阅读
  3. unity学习笔记 Restsharp 使用心得

    2024-03-18 19:04:01       44 阅读
  4. 一种不需要客户端ip的命令行远程工具

    2024-03-18 19:04:01       42 阅读
  5. 小程序 关闭小程序两种方式

    2024-03-18 19:04:01       40 阅读
  6. Nginx指令配置大全

    2024-03-18 19:04:01       45 阅读
  7. MySQL——InnoDB锁

    2024-03-18 19:04:01       40 阅读