Skip to content

Instantly share code, notes, and snippets.

@bcjordan
Last active December 28, 2015 17:39
Show Gist options
  • Save bcjordan/7537486 to your computer and use it in GitHub Desktop.
Save bcjordan/7537486 to your computer and use it in GitHub Desktop.
Level order print problem solutions

Submitted solutions

  • Rohit Jamuar in Python (gist)
  • Damir Bucar in Java (gist)
  • Pete Huang in Ruby (imgur) (single-array output)

  • Luís Armando Bianchin in Python (gist) (neat python list comprehensions!—an expected followup question would be: "can you do this without accessing the children twice per level?")
  • Bernie Margolis in Java (gist) (neat interfaces! uses lists on different levels of the call stack with recursion to track level advance)
  • Travis Jones in C (gist) and explanation with pictures (wild technique!)
  • Ankit Goyal in Ruby (gist) (uses counter to track when row is over)
  • Michael Penkov in Python (gist) (stores node level paired with children) "The solution is pretty ordinary: it's an iterative breadth-first search. I keep track of the level of each node I'm traversing. This is quite wasteful: I didn't think of using sentinels as in the sample solution. Given that BFS is generally memory-limited, sentinels are definitely the way to go."
  • Asim Ihsan in Java (imgur of initial thinking, gist (collects nodes until seeing sentinel, then prints and adds new level-indicating sentinel)
  • Denis Karpenko in Ruby (gist) (maps levels to values, then frees up memory early)
  • Omid Houshyar in Perl (gist)

Problem

Last week's question was to print a binary tree of integers in level order.

Level-order printing means printing each row of the tree from left to right, from root row to the deepest row. After each row, print a newline.

For example:

Bonus 1: Make one version that supports binary trees, and another that can handle any K-ary tree

Bonus 2: Submit your solution to Blake Embrey's problem repository

@dmnugent80
Copy link

Found some good algorithms here:
http://leetcode.com/2010/09/printing-binary-tree-in-level-order.html

First solution uses two queues, the other solution uses just one queue.
I implemented the one queue solution here:
https://gist.github.com/dmnugent80/3276172fdf0de44d637f

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment