Java 如何检查树中的节点是否有0或2个子节点?
我想知道我是如何理解这一逻辑的。我如何知道节点是否有0或2个子节点?这就是我到目前为止所做的,检查节点t是否有一个左右子节点Java 如何检查树中的节点是否有0或2个子节点?,java,binary-search-tree,Java,Binary Search Tree,我想知道我是如何理解这一逻辑的。我如何知道节点是否有0或2个子节点?这就是我到目前为止所做的,检查节点t是否有一个左右子节点 public static boolean hasChildren(Node t) { if (t.left == null && t.right == null){ return true; } return false; } 你需要这样的东西吗: public static int hasChildren(N
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;
}
}
return (t.left == null) == (t.right == null);
当
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) {
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);
像这样
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);
或者对于严肃的极客,比如:
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;
}
}
return (t.left == null) == (t.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个子节点的节点只有在(较大的子节点的大小@yummyyenni)时才有效,那么基于树大小的问题要困难得多。你最好将计数存储在节点中,以避免一直重新计算它们。你可能想先尝试解决这个问题,如果解决方案不起作用,再发布另一个问题。