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 };
  • 相关阅读:
    winston写日志(译)
    H5打字机特效
    Flutter 手指放大 平移 旋转 Widget
    51nod1432【贪心】
    死锁的例子
    C# SpinLock用法。
    鼓音效
    rm-rf
    cdoj 1334 郭大侠与Rabi-Ribi Label:贪心+数据结构
    1092 回文字符串(51nod)
  • 原文地址:https://www.cnblogs.com/infinityu/p/3073459.html
Copyright © 2011-2022 走看看