0

I am writing the code to calculate minimum depth of binary tree
My solution works well for tree BST if the inputs are 6,4,9,3,5,7,12,2,8
because minimum depth is coming as 3 which is correct.
But when the tree is 3,2 , minimum depth is coming as 1 instead of 2.
My code snippet is:

int minimumHeightRec(TreeNode root)
        {
            if(root == null) return 0;
            int left = minimumHeightRec(root.left);
            int right = minimumHeightRec(root.right);
            if(left > right) return right + 1;
            else return left + 1;
        }
2
  • When you say "when the tree is 3,2" do you mean the input? In that case, the root node will be "3" and the left node will be "2", while the right node will be null; in which case, returning 1 as minimum tree depth is correct. Commented Oct 17, 2015 at 20:01
  • yes ..................................... Commented Oct 18, 2015 at 1:43

2 Answers 2

1

Your implementation is correct. The expected minHeight should be 1 instead of 2. Consider your example of [3, 2] the BST may have the following form:

  3
 /
2

looking into left of root has height of 2: (3) -> (2)

looking into right of root has height of 1: (3)

You're looking for the minHeight of the BST, so taking the right branch of height 1 is the correct choice.

Note that you may have a different tree form where 2 is the root, but the logic and result will be the same.

Sign up to request clarification or add additional context in comments.

4 Comments

But i solved this question in Leetcode and its showing wrong. Refer leetcode.com/problems/minimum-depth-of-binary-tree
I see where the difference is, in the link you provided they define depth down to a leaf nodes which must have zero child. Which means in the case of [3, 2] root does not count, since root (3) has a child (2). Hope this helps.
I don't see how the tree you've written, Ling Zhong, has a right branch. There's only one root (3) and one left branch with a leaf (2). There's no right branch.
@ZaphodBeeblebrox I should phrase it better, it's more of looking into right of root. Please see edit.
0
  • The else is useless because there is a return in the if.
  • Some more code (TreeNode class and main) would be usefull.

1 Comment

The else actually improves readability since it makes it explicit under which condition it will be reached.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.