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 };
  • 相关阅读:
    Redis面试题
    Mysql面试题
    Mybatis面试题
    Springmvc面试题
    spring常见面试题
    优雅的参数校验
    Linux安装mongodb
    Redis缓存的雪崩、穿透、击穿
    语音识别(LSTM+CTC)
    大数据利器Hive
  • 原文地址:https://www.cnblogs.com/fresh-coder/p/14228804.html
Copyright © 2011-2022 走看看