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

    输入: (1,2,3,4,5)  输出:2

    代码:

     1 /**
     2  * struct TreeNode {
     3  *    int val;
     4  *    struct TreeNode *left;
     5  *    struct TreeNode *right;
     6  * };
     7  */
     8 
     9 class Solution {
    10 public:
    11     /**
    12      * 
    13      * @param root TreeNode类 
    14      * @return int整型
    15      */
    16     int run(TreeNode* root) {
    17         if( root == NULL)
    18             return 0;
    19         if( root->left == NULL && root->right == NULL)
    20             return 1;
    21         // 当左/右子树为空时,要找到该子树深度
    22         if( root->left == NULL || root->right == NULL)
    23             return max(run(root->left), run(root->right))+1;
    24         return min(run(root->left), run(root->right))+1;
    25     }
    26 };

    我的笔记:

      利用递归的方法找到最小深度,但会有左/右子树为空的情况,会干扰比较,所以需要单独将这种情况做处理,即:找到该子树的深度。

  • 相关阅读:
    Ext.grid.行相关
    FORM 布局
    rs.open sql,conn,1,1全接触
    arguments.callee
    Ext.window.MessageBox xtype: messagebox ; Ext.Msg Ext.MessageBox
    Ext.grid.column
    sql
    正则
    转JS
    quickFilters
  • 原文地址:https://www.cnblogs.com/john1015/p/13216551.html
Copyright © 2011-2022 走看看