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 };
  • 相关阅读:
    CLR via C# 3rd Edition下载
    SQL中的CASE WHEN语句
    为何要写注释?
    插件购票的公平性分析
    数据查询
    国产操作系统的市场运作策略
    0/0=2?
    为什么0.1无法被二进制小数精确表示?
    .net 可能要遭到取缔
    思考问题要先注意主体
  • 原文地址:https://www.cnblogs.com/infinityu/p/3073459.html
Copyright © 2011-2022 走看看