博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
LeetCode(111) Minimum Depth of Binary Tree解题报告
阅读量:4134 次
发布时间:2019-05-25

本文共 827 字,大约阅读时间需要 2 分钟。

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.

解题思路:

递归求解,如果有比min还小的深度,就更新min,需要注意的是,最小深度是叶子节点到根节点的深度。如果左子树或右子树为空,那么这个就不能计算在内。

public class Solution {    int min;    public int minDepth(TreeNode root) {        min = Integer.MAX_VALUE;        DepthOfTree(root,0);        return min;    }    public void DepthOfTree(TreeNode root,int depth){        if(root == null){            if(min > depth)                min = depth;            return ;        }        if(root.left == null)            DepthOfTree(root.right,depth+1);        else if(root.right == null)            DepthOfTree(root.left,depth+1);        else{            DepthOfTree(root.left,depth+1);            DepthOfTree(root.right,depth+1);        }    }}

转载地址:http://gtivi.baihongyu.com/

你可能感兴趣的文章
JavaScript setTimeout() clearTimeout() 方法
查看>>
CSS border 属性及用border画各种图形
查看>>
转载知乎-前端汇总资源
查看>>
JavaScript substr() 方法
查看>>
JavaScript slice() 方法
查看>>
JavaScript substring() 方法
查看>>
HTML 5 新的表单元素 datalist keygen output
查看>>
(转载)正确理解cookie和session机制原理
查看>>
jQuery ajax - ajax() 方法
查看>>
将有序数组转换为平衡二叉搜索树
查看>>
最长递增子序列
查看>>
从一列数中筛除尽可能少的数,使得从左往右看这些数是从小到大再从大到小...
查看>>
判断一个整数是否是回文数
查看>>
经典shell面试题整理
查看>>
腾讯的一道面试题—不用除法求数字乘积
查看>>
素数算法
查看>>
java多线程环境单例模式实现详解
查看>>
将一个数插入到有序的数列中,插入后的数列仍然有序
查看>>
在有序的数列中查找某数,若该数在此数列中,则输出它所在的位置,否则输出no found
查看>>
万年历
查看>>