Skip to content

Solution #199 - Daniel/Edited - 17.03.2025 #38

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -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.
Comment on lines +1 to +16
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can be much better! utilize Markdown and try to explain each step + Complexities.

Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
class Solution {
public:
vector<int> leftView(Node *root) {
vector<int> result;
traverse(root, 0, result);
return result;
}
void traverse(Node* root, int level, vector<int>& 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);
}
};