Java 二叉树上的迭代

Java 二叉树上的迭代,java,binary-tree,Java,Binary Tree,我想知道如何对二叉树进行迭代,以接收其中的元素数 这是我目前的代码: public static int Iteration(Node<Integer> node){ if(node.getRight() != null && node.getLeft() != null) return Iteration(node.getRight()) + Iteration(node.getLeft()) + count++; else if(n

我想知道如何对二叉树进行
迭代
,以接收其中的元素数

这是我目前的代码:

public static int Iteration(Node<Integer> node){
    if(node.getRight() != null && node.getLeft() != null)
        return Iteration(node.getRight()) + Iteration(node.getLeft()) + count++;
    else if(node.getRight() != null && node.getLeft() == null)
        return Iteration(node.getRight()) + count++;
    else if(node.getLeft() != null && node.getRight() == null)
        return Iteration(node.getLeft()) + count++;
    else
        return count;
}
公共静态int迭代(节点){
if(node.getRight()!=null&&node.getLeft()!=null)
返回迭代(node.getRight())+迭代(node.getLeft())+count++;
else if(node.getRight()!=null&&node.getLeft()=null)
返回迭代(node.getRight())+count++;
else if(node.getLeft()!=null&&node.getRight()=null)
返回迭代(node.getLeft())+count++;
其他的
返回计数;
}

这应该可以做到:

public static int countElements(Node<Integer> node) {
    if(node == null) return 0;

    // Left children plus right children plus current node    
    return countElements(node.getLeft()) + countElements(node.getRight()) + 1;
}
如果使用
countElements(nodeA)
调用该方法,它将递归调用
countElements(B)
countElements(C)

countElements(B)
依次调用其两个子项的方法,这两个子项都为null,因此方法调用结果为0
countElements(B)
返回
0+0+1
,等于1

对于
countElements(C)
它的工作方式相同,只有更深一层--
countElements(C)
返回3


countElements(A)
现在返回
1+3+1
,该值等于5,也是树中的节点数。

这是递归地进行预排序遍历以获得节点计数

public static int getNodeCount(Node<Integer> node){
    int count = 1;
    if(node.getRight() != null)
        count += getNodeCount(node.getRight());
    if(node.getLeft() != null)
        count += getNodeCount(node.getLeft());

    return count;
}
public static int getNodeCount(节点){
整数计数=1;
if(node.getRight()!=null)
count+=getNodeCount(node.getRight());
if(node.getLeft()!=null)
count+=getNodeCount(node.getLeft());
返回计数;
}

它不起作用。它不会累加元素的数量,如果累加的话,它会返回从根到叶的可能性数量,乘以2。我忘记了一个
+1
,刚刚编辑了它,你试过了吗?是的,返回可能性数量,乘以2。你能详细说明一下吗?我看不出这可能是什么结果我要搜索的是,二叉树中实际节点的数量。让我们取一个4×4的度量二叉树。其中有4个!节点。您发送给我的代码计算从根到底的节点数。但是,它在某些节点上重复,结果是一个类似于从根到达底部的可能性数量的数字。它返回从根到达底部的可能性数量,乘以2。而不是节点计数。
private node right
公共节点getRight(){返回this.right;}
public static int getNodeCount(Node<Integer> node){
    int count = 1;
    if(node.getRight() != null)
        count += getNodeCount(node.getRight());
    if(node.getLeft() != null)
        count += getNodeCount(node.getLeft());

    return count;
}