Tuesday, July 11th

 On to my second week of blogging!

Today's programming challenge was a medium difficulty made up of two easy difficulties

Given a binary tree, a target node of the tree, and a number of hops, return the collection of nodes that are the number of hops away from the target node

The main point behind today's problem is how to traverse a binary tree in reverse, that is, how to go from a child to a parent.  

Since the data structure is a binary tree, there isn't an immediate way to traverse backwards from the tree.  So we create a graph of undirected edges using depth first search

unordered_map<int, vector<int> > adjlist;
void dfs(TreeNode* node) {
int u=node->val;
if(node->left!=NULL) {
int v=node->left->val;
adjlist[u].push_back(v);
adjlist[v].push_back(u);
dfs(node->left);
}
if(node->right!=NULL) {
int v=node->right->val;
adjlist[u].push_back(v);
adjlist[v].push_back(u);
dfs(node->right);
}
return;
}

With the graph created, we can then perform another traversal to identify the nodes a certain number of hops from the target.  While DFS is an option and requires less code, we use breadth-first search, which is easier to associate with hops from a root node

vector<int> ans; //answer
void bfs(TreeNode *target, int hops) {
if(hops==0) {
ans.push_back(target->val);
return;
}

int root_id = target->val;
int depth=0;
queue<int> q;
vector<int> neighbors = adjlist[root_id];
for(int i=0; i<neighbors.size(); i++) {
q.push(neighbors[i]);
}
unordered_map<int, bool> visited;
visited[root_id]=true;
int qsize, u,v;
while(!q.empty()) {
depth++;
qsize=q.size();
if(depth==hops) {
for(int i=0; i<qsize; i++) {
ans.push_back(q.front());
q.pop();
}
return;
}
for(int i=0; i<qsize; i++) {
u=q.front();
q.pop();
visited[u]=true;
neighbors=adjlist[u];
for(int j=0; j<neighbors.size(); j++) {
v=neighbors[j];
if(visited.find(v)==visited.end() ) {
q.push(v);
}
}
}

}
return;
}

Returning the answer vector solves the problem.

The problem was marked as medium but is just made up of two straight-forward graph traversals

Comments

Popular posts from this blog

Wednesday, September 20th

Monday, September 11th

Tuesday, September 19th