Leetcode:minimum-depth-of-binary-tree

来源:互联网 发布:全球hr软件排名 编辑:程序博客网 时间:2024/06/03 18:31

题目描述:

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.


思路:

树的最小深度和最大深度不同,最大深度不需要考虑当前子树是否为单子树,因为最大深度等于左右子树的最大值;而最小深度需要考虑单子树的问题,若当前子树是单子树,那么最小深度就是单子树的深度,双子树的最小深度是左右子树的最小值。


代码:

/** * Definition for binary tree * public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode(int x) { val = x; } * } */public class Solution {    public int run(TreeNode root) {        if (root == null)            return 0;                if (root.left == null && root.right == null)            return 1;                if (root.left == null)            return run(root.right)+1;                if (root.right == null)            return run(root.left)+1;                return Math.min(run(root.left),run(root.right))+1;    }}


原创粉丝点击