简体   繁体   中英

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.

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".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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