minimum-depth-of-binary-tree

来源:互联网 发布:ant java fork 编辑:程序博客网 时间:2024/05/16 11:28

1、链接: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.

2、思路:递归,以当前根结点为根的最小高度为 1+Min{左子树最小高度,右子树最小高度}
3、代码:

public class Solution {    public int run(TreeNode root) {        if(root == null)            return 0;        return minimumDepth(root);    }    private int minimumDepth(TreeNode root) {        if(root.left == null && root.right == null){            return 1;        }        if(root.left == null)            return 1 + minimumDepth(root.right);        if(root.right == null)            return 1 + minimumDepth(root.left);        return 1+Math.min(minimumDepth(root.left), minimumDepth(root.right));    }}