zoukankan      html  css  js  c++  java
  • LeetCode111.二叉树的最小深度

    题目

    深度优先搜索

     1 class Solution {
     2 public:
     3     int minDepth(TreeNode* root) {
     4         if(root == NULL) return 0;
     5         if(root->left == NULL) return minDepth(root->right)+1;
     6         if(root->right == NULL) return minDepth(root->left)+1;
     7         return min(minDepth(root->left),minDepth(root->right)) + 1;
     8     }
     9     
    10 };

    广度优先搜索

     1 class Solution {
     2 public:
     3     int minDepth(TreeNode* root) {
     4         if(root == NULL) return 0;
     5         
     6         queue<pair<TreeNode* ,int>>que;
     7         que.emplace(root,1);
     8         while(!que.empty()){
     9             TreeNode* node = que.front().first;
    10             int depth = que.front().second;
    11             que.pop();
    12             if(node->left == NULL && node->right == NULL) return depth;
    13             if(node->left != NULL) que.emplace(node->left,depth+1);
    14             if(node->right != NULL) que.emplace(node->right,depth+1);
    15         }
    16         return 0;
    17     }
    18     
    19 };
  • 相关阅读:
    css3
    jquery常用的几种配置
    1808第一周笔记
    webpack打包的用法
    模块的使用及几类方式
    node的规范(common.js)
    模块化开发
    传统开发模式的缺点
    创建百度地图
    离线缓存总结
  • 原文地址:https://www.cnblogs.com/fresh-coder/p/14228804.html
Copyright © 2011-2022 走看看