3

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

1 Answer 1

5

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.