Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/meteor/3.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 二叉树中出现的计数_Java_Data Structures - Fatal编程技术网

Java 二叉树中出现的计数

Java 二叉树中出现的计数,java,data-structures,Java,Data Structures,假设一个二叉树可以有多个具有相同密钥的节点。计算其键等于值v的节点数。(它不是二叉搜索树) int countVal(int v):返回节点数n,其中n.key=v 结构: public class Tree { Node root; public Tree(Node root) this.root = root; } public static class Node { int key; Node left;

假设一个二叉树可以有多个具有相同密钥的节点。计算其键等于值v的节点数。(它不是二叉搜索树)

int countVal(int v):返回节点数n,其中n.key=v

结构:

public class Tree {
    Node root;

    public Tree(Node root) 
        this.root = root;
    }

    public static class Node {
        int key;
        Node left;
        Node right;

        public Node(int key, Node left, Node right) {
            this.key = key;
            this.left = left;
            this.right = right;
        }
    }
}

当然,解决方法是使用递归,但我找不到正确的方法。

这就是问题的解决方案:

public int countVal(int v) {
    if(root == null)
        return -1;
    else
        return countValRec(v, root);
}

private int countValRec(int v, Node node) {
    if(node == null)
        return 0;
    else if(node.key == v)
        return nodeCountValRec(v, node.left) + 1 + nodeCountValRec(v, node.right);
    else
        return nodeCountValRec(v, node.left) + nodeCountValRec(v, node.right);
}

我看不到有人企图这样做。许多教程都介绍了遍历树。就是这样一种资源。你可以通过简单的搜索找到很多这样的东西。