Given a Binary Tree, print left view of it. Left view of a Binary Tree is set of nodes visible when tree is visited from left side. Left view of following tree is 12, 10, 25.
12 / \ 10 30 / \ 25 40
Solution:
The left view contains all nodes that are first nodes in their levels. A simple solution is to do level order traversal and print the first node in every level.
The problem can also be solved using simple recursive traversal. We can keep track of level of a node by passing a parameter to all recursive calls. The idea is to keep track of maximum level also. Whenever we see a node whose level is more than maximum level so far, we print the node because this is the first node in its level (Note that we traverse the left subtree before right subtree).
Note: the same procedure can be used to get the "right view" of a tree if we first traverse the right sub-tree in the recursive algorithm.
// Recursive function to print left view of a binary tree. void leftViewUtil(struct node *root, int level, int *max_level) { // Base Case if (root==NULL) return; // If this is the first node of its level if (*max_level < level) { printf("%d\t", root->data); *max_level = level; } // Recur for left and right subtrees leftViewUtil(root->left, level+1, max_level); leftViewUtil(root->right, level+1, max_level); } // A wrapper over leftViewUtil() void leftView(struct node *root) { int max_level = 0; leftViewUtil(root, 1, &max_level); }
Complexity:
time - O(n)Links and credits:
space - O(n)
http://www.geeksforgeeks.org/print-left-view-binary-tree/
No comments:
Post a Comment