有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

我需要在java中找到树的节点总数

我将收到类似于:

public int count (Tree myTree){
}

我已经有了树定义,getLeft()getRight()方法

我看过一些例子,但它们总是接收一个节点作为参数,我需要接收Tree作为参数

谁能帮帮我吗?这个话题我是新手

谢谢


共 (4) 个答案

  1. # 1 楼答案

    在这里count (Tree myTree){ }

    Tree只是节点类,您将收到根节点作为参数,这里是myTree

    因为没有根节点,就不可能访问树。 在java集合中没有Tree这样的东西。所以请放心,你走上了正确的道路

  2. # 2 楼答案

    一棵树实际上是由它的根节点定义的,但是让我们假设你以自己的方式实现了这棵树:p并且你有一个函数来获取根getRoot(),您可以按如下方式使用递归来计算树中的节点数(我们假设,对于一个节点,您可以通过getLeft()getRight()访问子节点,您必须实现一个函数来从节点constructTree(Node root)构建树):

    public int count (Tree myTree){
       Node root = myTree.getRoot();
       return root != null ?
         1 + count(constructTree(root.getLeft()) + 
         count(contructTree(root.getRight()))
         : 0;
    }
    
  3. # 3 楼答案

    这里的Tree是节点类本身,这意味着名称的命名方式不同。 myTree参数是给定二叉树的一个节点,这里指向给定函数的根

    Binary Tree

    现在,节点类本身在下面的图片中,右子节点和左子节点以及当前节点的数据都存储在这里

    enter image description here

    所以要找出给定树的节点数

    您必须首先检查给定的myTree是否为空,这意味着给定的myTree是否只有根节点。 然后你必须返回0

    int count(Tree myTree)  
    {  
        if (myTree == null)  
        return 0;  
    
        int res = 0;  
        if (myTree.left != null && myTree.right != null)  
        res++;  
    
        res += (count(myTree.left) + count(myTree.right));  
        return res;  
    }  
    

    希望能有帮助:D

  4. # 4 楼答案

    假设Tree==Node,就像您描述的问题一样,那么一种方法是使用递归:

    public static int count(Tree tree) {
        Tree left = tree.getLeft();
        Tree right = tree.getRight();
        return 1 + 
            (left != null ? count(left) : 0) + 
            (right != null ? count(right) : 0);
    }