简体   繁体   English

JAVA - 打印节点+二叉搜索树的深度

[英]JAVA - Printing node + depth of a binary search tree

Im trying to print all values and depth for each node of my binary search tree.我试图为我的二叉搜索树的每个节点打印所有值和深度。 Im having trouble coming up with a way to count the depth recursively.我无法想出一种递归计算深度的方法。 So far I have a method for only printing each value of the tree.到目前为止,我有一种只打印树的每个值的方法。 I would appreciate some guidance because I feel like Im making it harder than it should be.我会很感激一些指导,因为我觉得我让它变得比应该的更难。

public void printTree( )
    {
        if( isEmpty( ) )
            System.out.println( "Empty tree" );
        else
            printTree( root );
    }

I do not see any code for printing the tree, but other than that the print function is not complete either.我没有看到任何用于打印树的代码,但除此之外,打印 function 也不完整。 To print the whole tree you can rely on any tree traversal algorithms.要打印整棵树,您可以依赖任何树遍历算法。 Here is sample code to return depth and print the tree in pre-order.这是返回深度并按预定顺序打印树的示例代码。

public static void printTree(Node r) {
    if( r==null )
        return;
    System.out.println(r.value);
    printTree(r.left);
    printTree(r.right);
}

public static int findDepth (Node r) {
    if(r==null)
      return 0;
    return (max(findDepth(r.left),findDepth(r.right))+1);
}

This is based assuming a Node class is defined as below.这是基于假设节点 class 定义如下。

class Node {
int value;
Node left;
Node right;

Node(int value) {
    this.value = value;
    right = null;
    left = null;
}

} }

you may need to build tree for testing in a separate function or inside main.您可能需要在单独的 function 或 main 内部构建测试树。

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

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