Finding the common ancestor in a binary tree

后端 未结 10 1195
悲哀的现实
悲哀的现实 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条回答
  •  旧时难觅i
    2021-02-09 03:29

    Set a pointer at both of the random nodes. Find the depth of each node by traversing to the top and counting the distance from the root node. Then set the pointer at both nodes again. For the deeper node, traverse up until both pointers are at the same depth. Then traverse up for both nodes until the pointers point to the same node. That is the ancestor node.

    By "traverse up" I just mean move the pointer to the parent of the current node.

    Edit to clarify: The key idea is that when both nodes are at the same depth, you can find the common parent very quickly just by simple traversal. So you climb the lower one until both are at the same depth, and then you traverse up. Sorry I don't really know C or I'd write code, but that algorithm should answer your question.

    Edit again: And my method runs in O(log(n)) time and O(1) memory.

    Another edit: O(log(n)) in a balanced tree. Worst-case performance is O(n) for an unbalanced tree. Thanks @DaveCahill

提交回复
热议问题