Thursday, June 12, 2014

Print a Binary tree in level order with new line after every level

Problem

Given a binary tree, you have to print level order traversal of the tree (left child then right child) but every next level has to be printed in next line.
Example
If the given tree is
    5

 10     15

56  47   12  42 
Then the output should be
5
10 15
56 47 12 42

Solution 

Here is the approach:
  1. Start with a root node. Add it to a new list.
  2. Now add all the children of the elements present in the new list and print the element, after removing the element. Once the array is empty, print the new line.

Here is the code
public void getLevelOrderInNewLine(TreeNode root)
{
    List<TreeNode> next = new ArrayList<TreeNode>();
    next.add(root);
    //actual function
    levelOrder(next);
}
public void levelOrder(List<TreeNode> n) {
    List<TreeNode> next = new ArrayList<TreeNode>();
    for (TreeNode t : n) {
        if (t != null) {
            System.out.print(t.getValue());
            next.add(t.getLeftChild());
            next.add(t.getRightChild());
        }
    }
    System.out.println();
    if(next.size() > 0)levelOrder(next);
}

References

0 comments:

Post a Comment