From 7f8225fac8f8e696482e899ea0a6c610dc411e9c Mon Sep 17 00:00:00 2001 From: danzang100 <12danysamuel@gmail.com> Date: Mon, 17 Mar 2025 22:47:23 +0530 Subject: [PATCH] Solution #199 - Daniel/Edited - 17.03.2025 --- .../Left and Right View/Explanation.md | 16 +++++++++++ .../Left and Right View/Solution.cpp | 28 +++++++++++++++++++ 2 files changed, 44 insertions(+) create mode 100644 Trees (Binary Trees)/Views of Trees/Left and Right View/Explanation.md create mode 100644 Trees (Binary Trees)/Views of Trees/Left and Right View/Solution.cpp diff --git a/Trees (Binary Trees)/Views of Trees/Left and Right View/Explanation.md b/Trees (Binary Trees)/Views of Trees/Left and Right View/Explanation.md new file mode 100644 index 0000000..198a3e6 --- /dev/null +++ b/Trees (Binary Trees)/Views of Trees/Left and Right View/Explanation.md @@ -0,0 +1,16 @@ +Left View of tree. + +Brute Force Approach: + +1. Perform a complete level order traversal of the tree and maintain a matrix of all nodes visited by level. +2. Choose only the first element for each level and return. + +Time Complexity: O(n) +Space Complexity: O(n) + +Optimal Approach: + +1. Perform DFS traversal of the tree prioritising the left subtree each time. +2. Take the first element of each level and return. + +For right view, repeat the same but take the last element of the matrix or perform DFS with the right subtree prioritised. diff --git a/Trees (Binary Trees)/Views of Trees/Left and Right View/Solution.cpp b/Trees (Binary Trees)/Views of Trees/Left and Right View/Solution.cpp new file mode 100644 index 0000000..13b0724 --- /dev/null +++ b/Trees (Binary Trees)/Views of Trees/Left and Right View/Solution.cpp @@ -0,0 +1,28 @@ +class Solution { + public: + vector leftView(Node *root) { + vector result; + traverse(root, 0, result); + return result; + } + void traverse(Node* root, int level, vector& res){ + //BRUTE FORCE APPROACH + if(root == NULL) return; + if(res.size() <= level){ + res.push_back({}); + } + res[level].push_back(root->data); + traverse(root->left, level+1, res); + traverse(root->right, level+1, res); + + //OPTIMAL APPROACH + if(!root) return; + + if(res.size() == level){ + res.push_back(root->data); + } + + traverse(root->left, level+1, res); + traverse(root->right, level+1, res); + } + }; \ No newline at end of file