57. Minimum Depth of Binary Tree

来源:互联网 发布:2k16捏脸数据科比 编辑:程序博客网 时间:2024/06/06 06:58

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.

注意:本题目求的是二叉树的根节点到叶子节点的最短路径。要保证最后终止的节点时叶子节点。当遇到类似于[1,2]这种,根节点缺少右子树的情况,则此时需要返回左子树的最小深度+1;如果根节点有两个孩子节点或者是没有孩子节点时则返回两个子树中较大者+1;如果根节点是空,则返回0

/** * 采用递归的思想做。当遇到类似于[1,2]这种,根节点缺少右子树的情况,则此时需要返回左子树的最小深度+1; * 如果根节点有两个孩子节点或者是没有孩子节点时则返回两个子树中较大者+1;如果根节点是空,则返回0 */public int minDepth(TreeNode root) {if(root == null){            return 0;        }else{        int ll = minDepth(root.left);        int rl = minDepth(root.right);        /*如果根节点只有一个孩子,则返回有孩子的那个深度+1,防止求出的结果不是根节点到叶子节点的深度*/        if(ll*rl == 0 && ll+rl!=0){        return Math.max(ll,rl)+1;        }else{/*其他情况就返回两个子树中深度较小的那个+1*/        return Math.min(ll, rl)+1;        }        }    }


0 0