LeetCode—Given a binary tree, find its minimum depth(二叉树,找到最小深度)—java

题目描述

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.

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

思路解析

三种情况:

  • 左右子树都为0:返回0
  • 只有一个子树为0:返回非空子树的深度
  • 左右子树都不为0:返回最小值

代码

/**
 * Definition for binary tree
 * 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;
        }
        int i=run(root.left);
        int j=run(root.right);
        return (i==0||j==0)?i+j+1:Math.min(i,j)+1;
    }
}

猜你喜欢

转载自blog.csdn.net/lynn_baby/article/details/80365961