zoukankan      html  css  js  c++  java
  • 力扣算法题—111.Minimum Depth of Binary Tree

     

    Given a binary tree, find its minimum depth.

    The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.

    Note: A leaf is a node with no children.

    Example:

    Given binary tree [3,9,20,null,null,15,7],

        3
       / 
      9  20
        /  
       15   7

    return its minimum depth = 2.

    Solution:

      使用深度遍历和广度遍历

     1 class Solution {
     2 private:
     3     int minLevel = INT32_MAX;
     4 public:
     5     int minDepth(TreeNode* root) {
     6         if (root == nullptr)return 0;
     7         //return BFS(root);
     8         int res = INT32_MAX;
     9         DFS(root, 1, res);
    10         return res;
    11     }
    12 
    13     int BFS(TreeNode* root)
    14     {
    15         queue<TreeNode*>q;
    16         q.push(root);
    17         int level = 0;
    18         while (!q.empty())
    19         {
    20             queue<TreeNode*>temp;
    21             ++level;
    22             while (!q.empty())
    23             {
    24                 TreeNode* p = q.front();
    25                 q.pop();
    26                 if (p->left == nullptr && p->right == nullptr)return level;
    27                 if (p->left != nullptr)temp.push(p->left);
    28                 if (p->right != nullptr)temp.push(p->right);
    29             }
    30             q = temp;
    31         }
    32         return level;
    33     }
    34     void DFS(TreeNode* root, int level, int &res)
    35     {
    36         if (root->left == nullptr && root->right == nullptr) {
    37             res = res > level ? level : res;
    38             return;
    39         }
    40         if (root->left != nullptr)DFS(root->left, level + 1, res);
    41         if (root->right != nullptr)DFS(root->right, level + 1, res);
    42     }
    43 
    44 };
  • 相关阅读:
    数据恢复基础知识
    Url传递中文终极解决办法
    用来实现Web页面图片移动托拽的代码段
    FAT文件系统原理
    SQL数据库恢复技术
    使用Ghost错选恢复分区后
    全手工数据恢复
    C#class的Dispose和Finalize模板
    SQL语句 嵌套查询
    逻辑数据库设计 无视约束(谈外键)
  • 原文地址:https://www.cnblogs.com/zzw1024/p/11756228.html
Copyright © 2011-2022 走看看