zoukankan      html  css  js  c++  java
  • [面试真题] LeetCode: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.

    分别考虑左右子树是否为空的情况并递归地进行计算。

    Program Runtime: 60 milli secs

     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         // Start typing your C/C++ solution below
    14         // DO NOT write int main() function
    15         if(NULL == root){
    16             return 0;
    17         }
    18         if(root->left != NULL && root->right == NULL){
    19             return minDepth(root->left) + 1;
    20         }else if(root->left == NULL && root->right != NULL){
    21             return minDepth(root->right) + 1;
    22         }else if(root->left == NULL && root->right == NULL){
    23             return 1;
    24         }else{
    25             int left = minDepth(root->left);
    26             int right = minDepth(root->right);
    27             return 1 + (left < right ? left : right);
    28         }
    29     }
    30 };
  • 相关阅读:
    SP1812 LCS2
    SP1811 LCS
    P3804 【模板】后缀自动机
    P3808 【模板】AC自动机(简单版)
    P3879 [TJOI2010]阅读理解
    P2602 [ZJOI2010]数字计数
    P4719 【模板】动态dp
    P1122 最大子树和
    P3554 [POI2013]LUK-Triumphal arch
    P3565 [POI2014]HOT-Hotels
  • 原文地址:https://www.cnblogs.com/infinityu/p/3073459.html
Copyright © 2011-2022 走看看