leetcode-Given a binary tree, find its minimum depth

第一题

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.

返回一个二叉树的最短深度,即从根节点到叶子节点的所有路径中中,包含最少节点的那条路径上的节点个数

public class Solution {
    public int run(TreeNode root) {
        if(root == null)
            return 0;
        int i = run(root.left);
        int j = run(root.right);
        return (i == 0 || j == 0) ? i+j+1 : Math.min(i, j)+1;
    }
}

  这段代码是网上大神的,使用了递归的思想。

  当遇到空节点(即叶子节点的子节点)时,返回0,表示叶子节点的子树的最短深度为0(叶子节点没有子树)。对于非叶子节点,利用run函数得到其左右子树的最短深度,将其中比较短的那条子树的最短深度+1(要加上本节点)后返回,特别的,如果其左右子树中的有一条为空,则返回非空子树的最短深度+1,只是因为当存在空子树时,过此点的最小深度路径之经过非空的那条子树。当然,如果左右子树都为空,说明当前节点为叶子节,返回值为1。

posted @ 2017-06-25 23:14  银河末班车  阅读(530)  评论(0编辑  收藏  举报