【发布时间】:2023-03-16 10:15:01
【问题描述】:
为使用中序遍历的二叉搜索树的高度编写了递归解决方案。
每次函数到达“null”节点(行尾)时,它都会重置名为“numLevels”的变量。每次方法到达行尾,如果numLevels > finalVar,则finalVar变成numLevels。
这是我的解决方案:
static int finalVar= 0;
static int numLevels= 0;
public static int height(Node root) {
// traverse (in order), ml++ with every recursive call, reset when node == null
findHeight(root);
if (finalVar-1 == 1) return 0; // special case defined in instructions
else{
return finalVar-1;
}
}
public static void findHeight(Node node){
numLevels++; // every time we recursive call, we add
if (node == null){
if (numLevels > finalVar){
finalVar=numLevels;
}
numLevels=0;
return;
}
findHeight(node.left);
findHeight(node.right);
}
所有其他测试用例都通过了。任何人都可以找出它不起作用的原因吗? :( 谢谢!
【问题讨论】:
-
你的递归方法应该返回一个值。您不需要为此使用静态变量。
标签: java data-structures binary-tree binary-search-tree testcase