Java 查找二叉树中大于x的节点数 公共静态int节点greaterthanx(二进制树节点根,int k,int计数) { if(root==null) 返回0; if(root.data>k){ System.out.print(root.data+“”); 计数++; } int countLeft=nodesGreaterThanX(root.left,k,count); int countRight=nodesGreaterThanX(root.right,k,count); 返回count+countLeft+countRight; } 公共静态void main(字符串[]args){ //TODO自动生成的方法存根 BinaryTreeNode root=takeInput(); int count=nodesGreaterThanX(根,2,0); System.out.println(); 系统输出打印项次(计数); }

Java 查找二叉树中大于x的节点数 公共静态int节点greaterthanx(二进制树节点根,int k,int计数) { if(root==null) 返回0; if(root.data>k){ System.out.print(root.data+“”); 计数++; } int countLeft=nodesGreaterThanX(root.left,k,count); int countRight=nodesGreaterThanX(root.right,k,count); 返回count+countLeft+countRight; } 公共静态void main(字符串[]args){ //TODO自动生成的方法存根 BinaryTreeNode root=takeInput(); int count=nodesGreaterThanX(根,2,0); System.out.println(); 系统输出打印项次(计数); },java,algorithm,recursion,data-structures,binary-tree,Java,Algorithm,Recursion,Data Structures,Binary Tree,我想得到大于x的节点数(在本例中为2),但我的答案不正确,我无法在程序中找到问题所在 如果不需要,请不要更改逻辑,并告诉我哪里出了问题。如果从根向下遍历树,则根本不需要向下传播“计数”——事实上,这样做会导致节点重复计数,因为它们对计数、左计数和右计数都有贡献,因为在传递给子节点的nodesGreaterThanX之前,您增加了count public static int nodesGreaterThanX(BinaryTreeNode<Integer> root,int k,in

我想得到大于x的节点数(在本例中为2),但我的答案不正确,我无法在程序中找到问题所在
如果不需要,请不要更改逻辑,并告诉我哪里出了问题。

如果从根向下遍历树,则根本不需要向下传播“计数”——事实上,这样做会导致节点重复计数,因为它们对
计数
左计数
右计数
都有贡献,因为在传递给子节点的
nodesGreaterThanX
之前,您增加了
count

public static int nodesGreaterThanX(BinaryTreeNode<Integer> root,int k,int count)
{
    if(root==null)
        return 0;
    if(root.data>k){
        System.out.print(root.data + " ");
        count++;
    }
    int countLeft = nodesGreaterThanX(root.left, k,count);
    int countRight = nodesGreaterThanX(root.right, k,count);

    return count + countLeft + countRight;
}

public static void main(String[] args) {
    // TODO Auto-generated method stub
    BinaryTreeNode<Integer> root = takeInput();
    int count = nodesGreaterThanX(root, 2,0);
    System.out.println();
    System.out.println(count);
}
公共静态int节点greaterthanx(二进制树节点,int k){
if(node==null){
返回0;
}
int countLeft=nodesGreaterThanX(node.left,k);
int countRight=nodesGreaterThanX(node.right,k);
返回(node.data>k?1:0)+countLeft+countRight;
}

您不需要通过调用树传递
count
变量,当您递归时,它会被一次又一次地计数

在每次通话中,您只需:

public static int nodesGreaterThanX(BinaryTreeNode<Integer> node, int k) {
  if (node == null) {
    return 0;
  }

  int countLeft = nodesGreaterThanX(node.left, k);
  int countRight = nodesGreaterThanX(node.right, k);

  return (node.data > k ? 1 : 0) + countLeft + countRight;
}

如果当前节点满足条件,则添加另一个
+1

您需要在三元组周围添加paren,以便在任何情况下都添加countLeft+countRight<代码>返回(node.data>k?1:0)+countLeft+countRight@MichaelMarkidis谢谢——已经有一段时间了,我想我不太记得优先规则了:)
return countLeft + countRight;