From 71a8ed4a23d36a1903695dc5cf277093a82d0d1f Mon Sep 17 00:00:00 2001 From: Vartika Gupta Date: Sun, 6 Nov 2022 11:50:49 +0530 Subject: [PATCH] code for left view of binary tree is added --- .../Trees/left_view_of_binary_tree.cpp | 60 +++++++++++++++++++ 1 file changed, 60 insertions(+) create mode 100644 algorithms/CPlusPlus/Trees/left_view_of_binary_tree.cpp diff --git a/algorithms/CPlusPlus/Trees/left_view_of_binary_tree.cpp b/algorithms/CPlusPlus/Trees/left_view_of_binary_tree.cpp new file mode 100644 index 00000000..978709c0 --- /dev/null +++ b/algorithms/CPlusPlus/Trees/left_view_of_binary_tree.cpp @@ -0,0 +1,60 @@ +#include +using namespace std; + +struct Node { + int data; + struct Node *left, *right; +}; + +struct Node* newNode(int item) +{ + struct Node* temp + = (struct Node*)malloc(sizeof(struct Node)); + temp->data = item; + temp->left = temp->right = NULL; + return temp; +} + + +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) { + cout << root->data << " "; + *max_level = level; + } + + // Recur for left subtree first, + // then right subtree + 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); +} + +// Driver Code +int main() +{ + Node* root = newNode(10); + root->left = newNode(2); + root->right = newNode(3); + root->left->left = newNode(7); + root->left->right = newNode(8); + root->right->right = newNode(15); + root->right->left = newNode(12); + root->right->right->left = newNode(14); + + leftView(root); + + return 0; +}