zoukankan      html  css  js  c++  java
  • leetcode 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.

    递归:

     1 /**
     2  * Definition for a binary tree node.
     3  * struct TreeNode {
     4  *     int val;
     5  *     TreeNode *left;
     6  *     TreeNode *right;
     7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     8  * };
     9  */
    10 class Solution {
    11 public:
    12     int minDepth(TreeNode* root) {
    13         if(root == NULL)
    14             return 0;
    15         if(root->left == NULL && root->right == NULL)
    16             return 1;
    17         if(root->left == NULL && root->right != NULL)
    18             return minDepth(root->right) + 1;
    19         if(root->left != NULL && root->right == NULL)
    20             return minDepth(root->left) + 1;
    21         else
    22             return min(minDepth(root->left), minDepth(root->right)) + 1;
    23         // if(root == NULL)
    24         //     return 0;
    25         // int l = minDepth(root->left);
    26         // int r = minDepth(root->right);
    27         // if(l == 0)
    28         //     return r + 1;
    29         // if(r == 0)
    30         //     return l + 1;
    31         // return (l < r ? l : r) + 1;
    32     }
    33 };

    bfs:

     1 /**
     2  * Definition for a binary tree node.
     3  * struct TreeNode {
     4  *     int val;
     5  *     TreeNode *left;
     6  *     TreeNode *right;
     7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     8  * };
     9  */
    10 class Solution {
    11 public:
    12     int minDepth(TreeNode* root) {
    13         if(root == NULL)
    14             return 0;
    15         int num = 0;
    16         queue<TreeNode*> q;
    17         TreeNode* temp;
    18         q.push(root);
    19         while(!q.empty()){
    20             num++;
    21             int len = q.size();
    22             while(len--){
    23                 temp = q.front();
    24                 q.pop();
    25                 if(temp->left == NULL && temp->right == NULL)
    26                     return num;
    27                 if(temp->left != NULL)
    28                     q.push(temp->left);
    29                 if(temp->right != NULL)
    30                     q.push(temp->right);
    31             }
    32         }
    33     }
    34 };
  • 相关阅读:
    (Go)11.九九乘法表示例
    (Go)10.流程控制示例
    (Go)09.指针赋值修改示例
    (Go)08.time示例
    (Go)07.strings与strconv的示例
    (Go)07.Go语言中strings和strconv包示例代码详解02
    (Go)06. Printf格式化输出、Scanf格式化输入详解
    kafka参数在线修改
    vs code golang代码自动补全
    JVM 方法区
  • 原文地址:https://www.cnblogs.com/qinduanyinghua/p/6413483.html
Copyright © 2011-2022 走看看