Skip to content
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
47 changes: 47 additions & 0 deletions Problem1.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
// Problem Name: level order traversal
// Time Complexity : O(n)
// Space Complexity : O(h) recursive stack space (height of the tree)
// Did this code successfully run on Leetcode : yes
// Any problem you faced while coding this : no

// Your code here along with comments explaining your approach
// 1. Here we can use any traversal, bfs or dfs
// 2. Here we use dfs traversal, we keep resizing our answer vector to the
// level, if they match
// 3. Process the elements can be done inorder, postorder or preorder
#include <bits/stdc++.h>
using namespace std;

/**
* Definition for a binary tree node.
*/
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode() : val(0), left(nullptr), right(nullptr) {}
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
TreeNode(int x, TreeNode *left, TreeNode *right)
: val(x), left(left), right(right) {}
};
class Solution {
public:
vector<vector<int>> levelOrder(TreeNode *root) {
vector<vector<int>> res;
if (!root)
return res;
dfs(root, res, 0);
return res;
}

void dfs(TreeNode *root, vector<vector<int>> &res, int level) {
if (!root)
return;
if (res.size() == level) {
res.resize(level + 1);
}
dfs(root->left, res, level + 1);
dfs(root->right, res, level + 1);
res[level].push_back(root->val);
}
};
48 changes: 48 additions & 0 deletions Problem2.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
// Problem Name: Course schedule
// Time Complexity : O(n)
// Space Complexity : O(n)
// Did this code successfully run on Leetcode : yes
// Any problem you faced while coding this : no

// Your code here along with comments explaining your approach
// 1. Here we use topo sort to compute the independent courses first, by pushing
// courses which have indegree of zero which means they are independent
// 2. By using BFS, we decrease the indegree of each neighbor node, if it comes
// to zero, we push to queue since they are now independent
// 3. In the end we check if count == numCourses, we return true

#include <bits/stdc++.h>
using namespace std;

class Solution {
public:
bool canFinish(int numCourses, vector<vector<int>> &pre) {
vector<vector<int>> adj(numCourses);
vector<int> indegrees(numCourses, 0);
for (auto it : pre) {
adj[it[1]].push_back(it[0]);
indegrees[it[0]]++;
}

queue<int> q;
for (int i = 0; i < numCourses; i++) {
if (indegrees[i] == 0) {
q.push(i);
}
}

int count = 0;
while (!q.empty()) {
int front = q.front();
q.pop();
count++;
for (auto nei : adj[front]) {
indegrees[nei]--;
if (indegrees[nei] == 0) {
q.push(nei);
}
}
}
return count == numCourses;
}
};