Minimum Depth of Binary Tree


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 /**
 2  * Definition for binary tree
 3  * public class TreeNode {
 4  *     int val;
 5  *     TreeNode left;
 6  *     TreeNode right;
 7  *     TreeNode(int x) { val = x; }
 8  * }
 9  */
10 public class Solution {
11     public int minDepth(TreeNode root) {
12         if(null == root){//空树
13             return 0;
14         }
15         else if(null != root && null == root.left && null == root.right)//只有根节点的树
16             return 1;
17         else if(null != root && null != root.left && null == root.right){//只有左子树
18             return minDepth(root.left) + 1;
19         }
20         else if(null != root && null == root.left && null != root.right){//只有右子树
21             return minDepth(root.right) + 1;
22         }else{//左右子树都有
23             int min = minDepth(root.left);
24             if(min > minDepth(root.right))
25                 min = minDepth(root.right);
26             return min + 1;
27         }
28     }
29 }

这道题主要是求根节点到叶子节点最短路径的长度,这里我借鉴了求树的深度算法。用的是递归实现的

如果是空树直接返回0

如果只有根节点返回1

如果只有左子树返回左子树的最短路径长度+1

如果只有右子树返回右子树的最短路径长度+1

如果有左右子树返回左右子树中最短路劲长度 + 1,这里需要比较左右子树最短路径长度,取最小那个返回

优质内容筛选与推荐>>
1、Git 中文乱码问题
2、【shell】shell编程(一)-入门
3、Windows Phone 7 网络编程之webclient和httpwebrequest的使用
4、推荐两篇分布式协调算法paxos的文章
5、在Apache下开启SSI配置支持include shtml html和快速配置服务器


长按二维码向我转账

受苹果公司新规定影响,微信 iOS 版的赞赏功能被关闭,可通过二维码转账支持公众号。

    阅读
    好看
    已推荐到看一看
    你的朋友可以在“发现”-“看一看”看到你认为好看的文章。
    已取消,“好看”想法已同步删除
    已推荐到看一看 和朋友分享想法
    最多200字,当前共 发送

    已发送

    朋友将在看一看看到

    确定
    分享你的想法...
    取消

    分享想法到看一看

    确定
    最多200字,当前共

    发送中

    网络异常,请稍后重试

    微信扫一扫
    关注该公众号





    联系我们

    欢迎来到TinyMind。

    关于TinyMind的内容或商务合作、网站建议,举报不良信息等均可联系我们。

    TinyMind客服邮箱:support@tinymind.net.cn