我想知道如何去做这个逻辑。我如何知道一个节点是否有0或2个孩子?这是我迄今为止所做的,检查节点t是否有左右孩子。如何检查树中的节点是否有0个或2个孩子?
public static boolean hasChildren(Node t) {
if (t.left == null && t.right == null){
return true;
}
return false;
}
我想知道如何去做这个逻辑。我如何知道一个节点是否有0或2个孩子?这是我迄今为止所做的,检查节点t是否有左右孩子。如何检查树中的节点是否有0个或2个孩子?
public static boolean hasChildren(Node t) {
if (t.left == null && t.right == null){
return true;
}
return false;
}
你需要的是这样的:
public static int hasChildren(Node t) {
if (t.left == null && t.right == null){
return 0;
} else if (t.left != null && t.right != null){
return 2;
} else {
return 1;
}
}
您正在寻找的时候left
和right
都是null
或当他们俩都没有null
那是真实的。这可以表示这样
if (t.left == null && t.right == null) {
return true;
}
if (t.left != null && t.right != null) {
return true;
}
return false;
这样
if ((t.left == null && t.right == null)
|| (t.left != null && t.right != null)){
return true;
}
return false;
这样
return (t.left == null && t.right == null)
|| (t.left != null && t.right != null);
或严重的爱好者,这样的:
return (t.left == null) == (t.right == null);
最后一个表达式认股权证一些讨论,因为我t比较left
和right
到null
,然后比较它们之间的这两个比较的结果以产生最终结果。
要查看是否在树中的所有节点有0或2名儿童,你将不得不递归地做到这一点:
public static boolean isLeafOrHasTwoChildren(Node t) {
// Both nulls
if (t.left == null && t.right == null) {
return true;
}
// One is null, the other one is not null
if (t.left == null || t.right == null) {
return false;
}
// Recurse down the tree
return isLeafOrHasTwoChildren(t.left)
&& isLeafOrHasTwoChildren(t.right);
}
没有问题。我还有另外一个问题,我很抱歉,我只想理解我的问题。如果具有2个孩子的节点仅在(大小较大的孩子<=孩子较小的孩子* 3)时有效?你需要找到一个节点的最大值和最小值? – yummyyenni
@yummyyenni基于树大小的问题要困难得多。在节点中存储计数以避免重新计算它们会更好。您可能首先尝试解决此问题,然后在解决方案无法正常工作时发布另一个问题。 – dasblinkenlight