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