Java 二叉树中出现的计数
假设一个二叉树可以有多个具有相同密钥的节点。计算其键等于值v的节点数。(它不是二叉搜索树) int countVal(int v):返回节点数n,其中n.key=v 结构: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;
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);
}
我看不到有人企图这样做。许多教程都介绍了遍历树。就是这样一种资源。你可以通过简单的搜索找到很多这样的东西。