繁体   English   中英

递归计算二叉搜索树中的节点数

[英]Recursively Count number of Nodes in Binary Search Tree

我试图能够在 int l 给定的级别上递归地计算二叉搜索树的节点数。 二叉树全是字符串,构造形式为

Node() {
   data;
   rChild;
   lChild; }

public Node getLeft() {return this.lChild;}

public Node getRight() { return this.rChild;)}

public Node getData() {return this.data; }
public void setData( String data) { this.data = data; }
public void setLeft( Node left) {this.lChild = left;}
public void setRight( Node right) {this.rChild = right;}

我试图创建的方法是在一个单独的类中,递归的,并且必须采用以下形式

countAtLevel( int l){}

我目前有

public int countAtLevel( int l) {
    if (this.root == null) {
        return 0;
    }
    if (level == 0) {
        return 1;
    }
    else {
        return this.getLeft().countAtLevel(l-1) + this.getRight().countAtLevel(l-1);
    }
}

但是,它会产生错误

错误:找不到符号方法:getLeft();

客户端代码将调用bst.countAtLevel(l)方法,并打印一个整数,例如对于二叉搜索树
.............3
............./\
............2 5
....../ / \
..........1..4 7

levelCount(0) 将返回 1,levelCount(1) 将返回 2,levelCount(2) 将返回 3

我似乎无法弄清楚什么是不对的。

您可能有一个容器类 Tree,并在其中保留一个 Node root字段。 这个 Tree 类具有递归方法countAtLevel

在树类中:

Node root;

public int count() {
    return countRecursively(root);
}

public int countRecursively(Node subtree) {
    if (subtree == null) {
        return 0;
    }
    return 1 + countRecursively(subtree.getLeft())
             + countRecursively(subtree.getRight());
}

countRecursively可以是Node的一种方法。

关于使用一个级别 然后你需要做一些奇怪的记账:不是所有的树的叶子都有相同长度的路径。

在 java 中,容器类使用int size()来给出元素的数量。 通常,它们在容器类中保留一个正在运行的计数器字段,因此size()很快。

您收到错误是因为countAtLevel()方法是为Node定义的, thisBinarySearchTree ,而不是Node

然而,这不是唯一的问题。 从您的代码中删除与“级别”相关的任何内容; 这没用。

相反,使用纯递归方法来计算树中的节点数:

public class BinarySearchTree {
    private Node root;
    public int size() {
        return root == null ? 0 : root.size();
    // other aspects of the class omitted
}

class Node {
    Node left;
    Node right;
    int size() {
        result = 1;
        result += left == null ? 0 : left.size();
        result += right == null ? 0 : right.size();
        return result;
    }     
    // other aspects of the class omitted
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM