• LeetCode OJ


    题目:

    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,若树为空返回0

    2,若树没有左子树,返回右子树的深度+1

    3,若树没有右子树,返回左子树的深度+1

    4,否则,返回min(左子树的深度,右子树的深度) + 1

    代码:

     1 /**
     2  * Definition for binary tree
     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) return 0;
    14         
    15         if (root->left == NULL) return minDepth(root->right) + 1;
    16         else if (root->right == NULL) return minDepth(root->left) + 1;
    17         else return min(minDepth(root->left), minDepth(root->right)) + 1;
    18     }
    19 };
  • 相关阅读:
    0615-temp-python web
    ResultSet 转ArrayList
    svn与git
    日期与时间
    springboot 注解
    函数式编程
    几个O
    springboot框架中的异步执行
    JDBC
    mysql 导出表结构
  • 原文地址:https://www.cnblogs.com/dongguangqing/p/3728061.html
Copyright © 2020-2023  润新知