Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/342.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 返回包含2个子节点的节点数_Java_Tree - Fatal编程技术网

Java 返回包含2个子节点的节点数

Java 返回包含2个子节点的节点数,java,tree,Java,Tree,我正在研究一个方法,该方法应该返回树中有两个子节点的节点数。这是我到目前为止所拥有的 public int twoChild(TreeNode<Integer> root){ if (root == null) return 0; else if (root.left != null && root.right != null) int leftTwoChild = twoChild(root.left);

我正在研究一个方法,该方法应该返回树中有两个子节点的节点数。这是我到目前为止所拥有的

public int twoChild(TreeNode<Integer> root){
    if (root == null)
        return 0;
    else if (root.left != null && root.right != null)
        int leftTwoChild = twoChild(root.left);
        int rightTwoChild = twoChild(root.right);
        return 1 + leftTwoChild + rightTwoChild;
public int-twoChild(TreeNode-root){
if(root==null)
返回0;
else if(root.left!=null&&root.right!=null)
int leftTwoChild=twoChild(root.left);
int rightwochild=twoChild(root.right);
返回1+leftTwoChild+rightTwoChild;

我不认为我拥有它,但我可能有正确的想法。如果有人能指导我如何做到这一点,我将不胜感激!

您必须分别测试每个子树。基本情况发生在当前树同时有两个子树时,我们将其作为最终结果的一个子树-但无论如何,我们必须继续遍历t的其余部分他是一棵树。这就是我的意思:

public int twoChild(TreeNode<Integer> root) {

    // base case: tree is empty
    if (root == null) return 0;

    // base case: tree has both children, or not    
    int count = root.left != null && root.right != null ? 1 : 0;

    // recursive cases: traverse both subtrees, accumulating result
    count += twoChild(root.left);
    count += twoChild(root.right);

    // return result of recurring on both subtrees
    return count;

}
public int-twoChild(TreeNode-root){
//基本情况:树为空
if(root==null)返回0;
//基本情况:树是否同时具有两个子项
int count=root.left!=null&&root.right!=null?1:0;
//递归案例:遍历两个子树,累积结果
计数+=twoChild(root.left);
count+=twoChild(root.right);
//返回两个子树上重复出现的结果
返回计数;
}

好的,我知道你做了什么。我更新了问题中的代码,尝试调整你使用的方法。现在,我之前做的大多数示例都对左右使用单独的变量,而不仅仅是一个计数器,所以我保留了这一点。在我这样做的地方有更好的方法吗,就像我的示例中有一个左计数器一样整数和右整数?这只是一个风格问题,它不会改变结果…但是你可以将每次递归调用的结果存储在一个单独的变量中,然后在末尾添加三个变量:
count
countLeft
countRight
。好吧,我现在的问题是有意义的,并且可以推进Ry work?@MirrandaRyan不,它不会工作,因为你在错误的地方声明了变量。测试它,尝试编译它,它会失败。我现在没有IDE,我只是在纸上做这个。我不认为有问题……请停止编辑原始问题,修复问题中的代码没有意义,它无效ides的答案。我将恢复到原来的代码,你已经得到了你的答案。