二叉树的最小深度

来源:互联网 发布:js fetch api 编辑:程序博客网 时间:2024/05/16 17:17

题目

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.

java实现

public int run(TreeNode root) {        if (root == null)//空树深度为0            return 0;        if (root.left == null && root.right == null)//只有一个节点            return 1;        int leftDepth = run(root.left);        int rightDepth = run(root.right);        if (leftDepth == 0)//左子树深度为0,返回右子树深度加1            return rightDepth + 1;        else if (rightDepth == 0)            return leftDepth + 1;        else            return Math.min(leftDepth, rightDepth) + 1;    }
原创粉丝点击