Interview Question

Software Engineer Interview

-Mountain View, CA

LinkedIn

Print out a binary tree with each level printed on its own line.

Answer

Interview Answers

4 Answers

3

Just print BFS

Anonymous on

0

BFS with some modification looks correct, but how would do this with in-order traversal?

Anonymous on

0

//Breadth First Search, traverse tree and print it out level-by-level public class TreeNode{ public int data; public int level; public TreeNode left; public TreeNode right; public TreeNode(int d, int l){ this.data = d; this.level = l; this.left = null; this right = null; } } public class BinaryTree{ public TreeNode root; public BinaryTree(){ this.root = null; } public void setLevels(TreeNode node, int l){ if (node != null){ node.level = l; setLevels(node.left, level + 1); setLevels(node.right, level + 1); } } public void printEachTreeLevel(TreeNode root){ Queue<div>treeQueue = new LinkedList<div>(); if (root == null){ return; } //set levels, just in case setLevels(root, 0); //Start Breadth first traversal of tree treeQueue.clear(); treeQueue.add(root); while (!(treeQueue.size() == 0)){ TreeNode node = treeQueue.remove(); System.out.print(node.data + " "); //If we are at the end of a level, start a new line if (node.level != treeQueue.peek().level){ System.out.println(); } if (node.left != null){ treeQueue.add(node.left); } if (node.right != null){ treeQueue.add(node.right); } } }</div></div>

Dan on

0

Figuring out that you need an in-order traversal isn't too tough. Figuring out where to put the line breaks takes a little more work. I solved it, with some help on that second part.

Anonymous on

Add Answers or Comments

To comment on this, Sign In or Sign Up.