How to print a binary tree level by level? Interview Question!

How to print a binary tree level by level?

This is an interview question I received today. Of course, using a BFS style will definitely work. However, the following question: how to print a tree using read-only memory? (Thus, no queue can be used)

I was thinking about converting a binary tree to a linked list, but did not come up with a specific solution.

Any suggestions?

thank

+5
source share
3 answers

( , ) - - , , . , , , , , .

, , , , " " .

+5

, , , - , . , .

:

Morris inorder

+3

You can do this by repeatedly traversing the tree in turn when printing only those nodes at a specified level. However, this is not strictly read-only memory, since recursion uses a call stack. And it is super inefficient. Like O (n * 2 ^ n) or something like that.

printLevel = 1;

while(moreLevels) {

    moreLevels = printLevel(root, 1, printLevel);
    printLevel++;
}

boolean printLevel(Node node, int currentLevel, int printLevel) {

    boolean moreLevels = false;

    if(node == null) {
        return(false);
    }

    else if(currentLevel == printLevel) {
        print the node value;
    }

    else {

        moreLevels |= printLevel(node.leftChild, currentLevel + 1, printLevel);
        moreLevels |= printLevel(node.rightChild, currentLevel + 1, printLevel);
    }

    return(moreLevels);
}
+1
source

All Articles