×

# KETYES - Editorial

Author: Chandan Boruah
Tester: Chandan Boruah
Editorialist: Chandan Boruah

SIMPLE

# PREREQUISITES:

Graph Theory, Graph Traversal

# PROBLEM:

Given a tree and a node, find the distance from the root to the node.

# QUICK EXPLANATION:

Traverse the tree using BFS or DFS and store the distance of each node from the root in a linked list, till the required node is found.

# EXPLANATION:

You need to find the distance of the given node from the root node (root node which is always 0). For that you have to start traversing the tree from the root node. For traversing the tree you can either use BFS or DFS (read more here). Every time a new node, lets say A, is found from another node, lets call it B, you add 1 to the distance of B from root and call it the distance of A from root. You store that distance in a linked list. When you find the required node you break from the loop, and print the required distance.

Following is the code with explanation in comments

        Stack<int>st=new Stack<int>();//declare a stack
List<int>dist=new List<int>();//declare another linked list to store distance of current node from popped node
st.Push(0);//pushing root node, the source node
while(st.Count>0)//till all nodes are visited this will run
{
int now=st.Pop();//popping current node
int curdist=dist[done.IndexOf(now)];//extracting distance of current node from root node
for(int i=0;i<n;i++)//iterating through all nodes
{

if(arr[now,i]==1)//if its neighbour of popped node then this will be true
{
{
st.Push(i);//push the node to the stack
}
}
}
}
Console.WriteLine(dist[done.IndexOf(find)]);//print the required distance


# AUTHOR'S AND TESTER'S SOLUTIONS:

Author's solution can be found above. Tester's solution can be found above.

13310
accept rate: 0%

19.6k349497539

 toggle preview community wiki:
Preview

By Email:

Markdown Basics

• *italic* or _italic_
• **bold** or __bold__
• image?![alt text](/path/img.jpg "title")
• numbered list: 1. Foo 2. Bar
• to add a line break simply add two spaces to where you would like the new line to be.
• basic HTML tags are also supported
• mathemetical formulas in Latex between \$ symbol

Question tags:

×15,182
×1,186
×1,131
×171
×170
×19
×1

question asked: 29 Mar '16, 19:34

question was seen: 887 times

last updated: 20 May '16, 11:41