Leetcode-minimum-depth-of-binary-tree

来源:互联网 发布:cf免费卡枪带软件 编辑:程序博客网 时间:2024/06/05 07:23

题目描述

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 TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode(int x) { val = x; } * } */public class Solution {    public int run(TreeNode root) {    if(root == null)    return 0;    if(root.left==null && root.right==null)    return 1;    if(root.left==null)    return run(root.right)+1;    if(root.right==null)    return run(root.left)+1;    return Math.min(run(root.left), run(root.right))+1;     }}

如代码所示:

根为空时,返回0;根的左孩子为空,返回根的右孩子深度+1;根的右孩子为空,返回根的左孩子深度+1;根的左右孩子都为空,返回1;根的左右孩子都不为空,返回根的左孩子深度与右孩子深度的小者+1。


0 0
原创粉丝点击