Why won't my solution work to find minimum depth of a binary tree?

只愿长相守 提交于 2020-01-14 19:34:09

问题


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

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;
}

回答1:


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

  3
 / \
   20
  /  \
 15   7

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

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



来源:https://stackoverflow.com/questions/52803500/why-wont-my-solution-work-to-find-minimum-depth-of-a-binary-tree

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!