为什么我的解决方案无法找到二叉树的最小深度? [英] Why won't my solution work to find minimum depth of a binary tree?

查看:75
本文介绍了为什么我的解决方案无法找到二叉树的最小深度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不了解我的用于查找二叉树最小深度的解决方案如何不起作用?我在做什么错了?

I don't understand how my solution for finding minimum depth of a binary tree doesn't work? What am I doing wrong?

如果您好奇的话,这里是问题的链接: https://leetcode.com/problems/minimum-depth-of-binary-tree/submissions/

Here's a link to the problem if you're curious: https://leetcode.com/problems/minimum-depth-of-binary-tree/submissions/

public int minDepth(TreeNode root) {
    if(root == null) return 0;

    int left = minDepth(root.left);
    int right = minDepth(root.right);

    int ans = Math.min(left, right) + 1;

    return ans;
}


推荐答案

您的代码将无法在如果只有一侧是 null ,例如

Your code will not work in the case only one side is null, like

  3
 / \
   20
  /  \
 15   7

因为它将返回1 (而 3 不是叶子)。

as it will return 1 (while 3 is not a leaf).

您需要测试一侧是否为 null ,忽略它并与另一边打交道

You need to test if one side is null, ignore it and deal with the other side

这篇关于为什么我的解决方案无法找到二叉树的最小深度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆