Minimum Depth of Binary Tree

来源:互联网 发布:sql语句update语句 编辑:程序博客网 时间:2024/06/05 17:33

题目描述:

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 a binary tree node. * public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode(int x) { val = x; } * } */class Solution {    public int minDepth(TreeNode root) {        if (root == null) {            return 0;        }        if (root.left == null && root.right == null) {            // 叶子节点            return 1;        }        int min = Integer.MAX_VALUE;        if (root.left != null) {            min = minDepth(root.left);        }        if (root.right != null) {            int minRight = minDepth(root.right);            min = min < minRight ? min : minRight;        }        return min + 1;    }}


原创粉丝点击