简体   繁体   English

编写打印二叉树和每个节点级别编号的方法

[英]Writing a method that print binary tree and each node level number

I need to write a method that prints a binary tree by using recursion. 我需要编写一个使用递归打印二叉树的方法。 It must be that the signature of the method will be 必须是方法的签名

public static void level(Node n)

so the method can get only the Node n and should not return anything, just print on screen. 所以该方法只能获得Node n,不应返回任何内容,只需在屏幕上打印即可。

My problem is: I need that each level on the tree will print with his own level number, and i dont know how to do this cause if i put a counting integer it zero every time the recursion start. 我的问题是:我需要树上的每个级别将使用他自己的级别号打印,并且我不知道如何执行此操作,如果我在每次递归开始时将计数整数设置为零。

this is what i tried: 这是我试过的:

public static void level(Node n)
{
    if (n.getLeftSon() == null && n.getRightSon() == null)
        System.out.println(n.getNumber());
    else
    {
        System.out.println(n.getNumber()); 
        if (n.getLeftSon() != null)
            level(n.getLeftSon());
        if (n.getRightSon() != null)
            level(n.getRightSon()); 
    }

}

it works printing the tree but without the levels number for each Node. 它可以打印树,但没有每个节点的级别编号。

OK so after help here in the forum i wrote this method like that: 好的,所以在论坛的帮助后,我写了这样的方法:

public static void level(Node n)
{
    levelAndNumbers(n,0);
}

private static void levelAndNumbers(Node n, int i)
{
    if (n.getLeftSon() == null && n.getRightSon() == null)
        System.out.println(n.getNumber()+"=>"+i);
    else
    {
        System.out.println(n.getNumber()+"=>"+i); 
        if (n.getLeftSon() != null)
            levelAndNumbers(n.getLeftSon(), i+1);
        if (n.getRightSon() != null)
            levelAndNumbers(n.getRightSon(), i+1); 
    }

}

and its working great! 它的工作很棒!

so from what i understand there is no way to do this only in the public method? 所以从我的理解,只有在公共方法中没有办法做到这一点? i have to add another private method that get also a counting number...??? 我必须添加另一个私人方法,也得到一个计数... ... ???

Almost what you already did but with the following fix. 几乎你已经做了什么,但有以下修复。

public static void level(Node n) {
    level(n, 0);
}

private static void level(Node n, int level) {
   ///..............your logic
   level(n.getLeftSon(), level + 1);
   //...............
   level(n.getRightSon(), level + 1);
}

BTW, more useful name when speaking about hierarchical structures is not "son" but "child". BTW,在谈到层次结构时更有用的名称不是“儿子”而是“孩子”。

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

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