Thursday, March 19, 2009

level order tree traversal

How would you print out the data in a binary tree, level by level, starting at the top?

Clue:
How about using a Queue. Relate to Dijkstra's SP algorithm.

1 comment:

  1. I think we can do it like this way
    ======================================
    PUSH QUEUE(ROOT)
    IF !ROOT
    PRINT POP QUEUE(ROOT)
    PUSH QUEUE(LEFT) && PUSH QUEUE(RIGHT)

    PRINT POP QUEUE(LEFT) && PUSH QUEUE LEFT(LEFT) && PUSH QUEUE RIGHT(LEFT)

    PRINT POP QUEUE(RIGHT) && PUSH QUEUE LEFT(RIGHT) && PUSH QUEUE RIGHT(RIGHT)

    Break when Queue is empty.

    Any better idea Kamlesh? I know you must have it.

    ReplyDelete