二进制树中出现次数计数

时间:2019-06-06 15:04:53

标签: 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;
        Node right;

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

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

1 个答案:

答案 0 :(得分:1)

这是解决问题的方法:

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);
}
相关问题