[英]Java: Minimum Depth of Binary search Tree Recursive
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 如果输入分别为6,4,9,3,5,7,12,2,8,我的解决方案对于树BST效果很好
because minimum depth is coming as 3 which is correct. 因为最小深度为3,这是正确的。
But when the tree is 3,2 , minimum depth is coming as 1 instead of 2. 但是,当树为3,2时,最小深度为1而不是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;
}
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:
预期的minHeight应该是1而不是2。考虑您的[3,2]示例,BST可能具有以下形式:
3
/
2
looking into left
of root
has height of 2: (3) -> (2) 向
root
left
,其高度为2:(3)->(2)
looking into right
of root
has height of 1: (3) 看着
root
right
高度为1:(3)
You're looking for the minHeight of the BST, so taking the right branch of height 1
is the correct choice. 您正在寻找BST的minHeight,因此采用正确的高度
1
分支是正确的选择。
Note that you may have a different tree form where 2
is the root, but the logic and result will be the same. 请注意,您可能具有不同的树形式,其中
2
为根,但是逻辑和结果将相同。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.