The nodes inthe levels are printed in the similar manner their parents were printed. So itshould be an FIFO queue to hold the level. I really don’t remember the functionname of the stl queue, so I will write it in Java...void printByLevel(Node root) { Node sentinel = new Node(); LinkedList<Node> q=newLinkedList<Node>(); q.addFirst(root); q.addFirst(sentinel); while (!q.isEmpty()) { Node n = q.removeLast(); if (n==sentinel) { System.out.println(“\n”); q.addFirst(sentinel); } else { System.out.println(n); if (n.left() !=null) q.addFirst(n.left()); if(n.right()!=null) q.addFirst(n.right()); } }}
共 1 个关于本帖的回复 最后回复于 2013-8-16 11:11