How can I find the depth of a specific node inside a binary tree?

Viewed 839

I'm trying to figure out a recursive solution to this problem. The main thing is to return the level in the binary tree where the node is.

def find_depth(tree, node):
    if node == None:
        return 0 
    else: 
        return max(find_depth(tree.left))
        #recursive solution here 

Using this class for the values:

class Tree:
    def __init__(self, value, left=None, right=None):
        self.value = value
        self.left  = left
        self.right = right

Example: Calling find_depth(tree, 7) should return the level where 7 is in the tree. (level 2)

   3
  / \
  7  1  <------ return that 7 is at level 2
 / \  
 9 3   
3 Answers

maybe this is what you are looking for

    def find_depth(tree, node):
        if node is None or tree is None:
            return 0

        if tree == node:
            return 1

        left = find_depth(tree.left, node)
        if left != 0:
            return 1 + left
        right = find_depth(tree.right, node)
        if right != 0:
            return 1 + right

        return 0

You need to provide information about depth in find_depth call. It might look like this (assuming 0 is a sentinel informing that node is not found):

def find_depth(tree, node, depth=1):
    if node == None:
        return 0

    if tree.value == node:
        return depth

    left_depth = find_depth(tree.left, node, depth+1)
    right_depth = find_depth(tree.right, node, depth+1)
    return max(left_depth, right_depth)

Then you call it with two parameters: x = find_depth(tree, 7).

Recursion is a functional heritage and so using it with functional style yields the best results -

  1. base case: if the input tree is empty, we cannot search, return None result
  2. inductive, the input tree is not empty. if tree.data matches the search value, return the current depth, d
  3. inductive, the input tree is not empty and tree.data does not match. return the recursive result of tree.left or the recursive result of find.right
def find (t = None, value = None, d = 1):
  if not t:
    return None              # 1
  elif t.value == value:
    return d                 # 2
  else:
    return find(t.left, value, d + 1) or find(t.right, value, d + 1) # 3

class tree:
  def __init__(self, value, left = None, right = None):
    self.value = value
    self.left = left
    self.right = right

t = tree \
  ( 3
  , tree(7, tree(9), tree(3))
  , tree(1)
  )

print(find(t, 7)) # 2
print(find(t, 99)) # None

You can implement the find method in your tree class too

def find (t = None, value = None, d = 1):
  # ...

class tree
  def __init__ #...

  def find(self, value)
    return find(self, value)

print(t.find(7)) # 2
print(t.find(99)) # None
Related