drunkmonkey
drunkmonkey

Reputation: 1181

Recursively find height of tree/ deepest node

Can anyone help walk me through finding the height of a tree by using a recursive depth first search? i.e find the deepest branch node? Thanks

Upvotes: 1

Views: 2140

Answers (1)

Grigor Gevorgyan
Grigor Gevorgyan

Reputation: 6853

Pseudocode:

dfs( v ):
1. visited[ v ] = true
2. max_child_depth = 0
3. for each u s.t. there's edge (v,u)
        if not visited[ u ]
        then max_child_depth = max( max_child_depth, dfs( u ))
4. return max_child_depth + 1

Upvotes: 2

Related Questions