# Can two neighbors in a graph be at the same depth in a DFS tree?

In an undirected graph, can two nodes at an identical distance n from the root of a DFS tree be neighbors in the original graph? I'm thinking no, but I'm not sure (because of back edges)

I think you are correct:

All neighbors of a node will be of rank one less (the node we got here from) or one more (or two more, etc) because we will rank them before we back out of the node.

• DFS and BFS visit edges in the same order under some constraints! In such cases neighbors in the tree are also neighbors in the graph. Correct me if I'm wrong.
– mrk
Commented Sep 24, 2012 at 16:54
• @saadtaame You are wrong. Commented Jan 1, 2016 at 5:19

The wikipedia article states that "it can be shown that if the graph is undirected then all of its edges are tree edges or back edges."

If you find out how this can be shown, you should be quite close to your solution.

• If the edge is not a back edge (an edge you walk back in on) than it will be a tree edge b/c you will walk out it.
– BCS
Commented Jan 6, 2009 at 0:21

Your question does not stipulate how the DFS tree is generated. Naive implementations simply list nodes in the order they are visited, but most practical implementations rebuild the output tree as the search progresses and the ranks of the nodes are adjusted.

Consider three nodes, A B C, connected to each other. A naive DFS will visit A B C, with ranks of 0 1 2, and the tree will have a back edge from C to A. A more useful implementation will backtrack from C to B to A, and then from A will travel to C again and assign it a rank of 1, then decline to travel to B at rank 2 because B is already rank 1, this tree will have both B and C at rank 1 below A, with a cross edge between B and C.

• this is not correct
– Joe
Commented Sep 25, 2012 at 0:41
• @Joe could you elaborate on that? In re-reading my example I see that it's not as clear as it might be, so I'd be happy to rewrite it if it is confusing to you. Commented Sep 26, 2012 at 16:51
• What you describe is more like a DFS followed by a BFS. Nodes that have already been visited are not re-visited in any standard DFS.
– Joe
Commented Sep 27, 2012 at 18:06
{"found_math": false, "script_math_tex": 0, "script_math_asciimath": 0, "math_annotations": 0, "math_alttext": 0, "mathml": 0, "mathjax_tag": 0, "mathjax_inline_tex": 0, "mathjax_display_tex": 0, "mathjax_asciimath": 0, "img_math": 0, "codecogs_latex": 0, "wp_latex": 0, "mimetex.cgi": 0, "/images/math/codecogs": 0, "mathtex.cgi": 0, "katex": 0, "math-container": 0, "wp-katex-eq": 0, "align": 0, "equation": 0, "x-ck12": 0, "texerror": 0}