[英]Calculating Max Imbalance of Binary Search Tree
我目前正在编码一种递归方法,以返回整个二叉搜索树上的最大不平衡量。 我对递归编程非常陌生,因此很难全神贯注。 我构建的树的不平衡度为1,但我的方法仅返回0。我确定此处的逻辑存在缺陷。
我100%确保在该方法的每个步骤中,它都在运行“(root == null){return 0;}”。 我尝试删除它并进一步定义它,并且它继续这样做。
这是我目前的方法:
public int getMaxImbalance(){
return Math.abs(getMaxImbalance(root));
}
public int getMaxImbalance (TreeNode<E> root){
if (root == null){
return 0;
}else if(root.left != null && root.right == null){
return 1 + getMaxImbalance(root.left) + getMaxImbalance(root.right);
//adds 1 left is true and right is false
}else if(root.left == null && root.right != null){
return -1 + getMaxImbalance(root.left) + getMaxImbalance(root.right);
//adds -1 left is false and right is true
}
return getMaxImbalance(root.left) + getMaxImbalance(root.right);
//calls itself if both fields are null;
}
代码中的逻辑似乎是错误的:节点的最大不平衡不是其子节点的最大不平衡之和。 相反,最大不平衡应该是其子节点的高度差的绝对值(如果其中一个为空,则该节点的最大不平衡度仅为0,因此当前节点的最大不平衡度完全取决于它的高度)唯一的孩子)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.