Finding the common ancestor in a binary tree

后端 未结 10 1073
悲哀的现实
悲哀的现实 2021-02-09 02:50

This question was asked to me in an interview: I have a binary tree and I have to find the common ancestor (parent) given two random nodes of that tree. I am also given a point

10条回答
  •  心在旅途
    2021-02-09 03:29

    I think you could just do a search simultaneously for both nodes; the point at which the search diverges is the common ancestor.

    commonAncestor tree a b:
      value := 
      if (a < value) && (b < value)
      then commonAncestor (left tree) a b
      else if (a > value) && (b > value)
      then commonAncestor (right tree) a b
      else tree
    

    Interestingly this approach would scale to more than two nodes (check for all of them to be on the left side of tree, etc.)

提交回复
热议问题