Wednesday, June 17, 2015

Print Left View of a Binary Tree

Left view of a Tree is: When you view the Tree from left side of the Tree, where you will be able to see only the first element in each level.

So other way of asking the question is: Print the first node in each Level of the Tree.

eg:
                              1
               2                               3
                     4                   5           6
               7                               8
                                         9
                                              10

Output: 1 2 4 7 9 10

Algorithm:

Logic is to keep a global variable called "level", with initial value as 0

Traverse the tree in PreOrder(DLR)

Now for each node, check whether its height is equal to count or not.

If equal, it means that this is the left most element in that level that we encountered. So print it and increase the count, so that other elements in the same height wont be printed.

Do this recursively.

Code:

class TreeLeftView {
        static int level = 0;

        static public void print(TreeNode root, int height) {
                if(root == null)
                        return;

                if(level == height) {
                        System.out.print(root.getData() + " ");

                        ++level;
                }

                print(root.getLeft(), height + 1);
                print(root.getRight(), height + 1);
        }

        static public void main(String[] args) {
                TreeNode root = TreeUtil.getBinaryTree2();

                print(root, 0);

                System.out.println();
        }
}

No comments:

Post a Comment