Design an algorithm and write code to find the first common ancestor of two nodes in a binary tree. NOTE: This is not necessarily a binary search tree.
Approach:
Do the inorder traversal and store it in an array I
Then do the preorder traversal and store it in an array P
Inorder: D B F G E A C
PreOrder: A B D E F G C
Suppose we need to find LCA for nodes D and F
mark the positions in inorder array and find first preorder ptr which seprates it into two
different parts of Inorder array
for above example first preorder ptr is "B" which seprates inorder into "D" and "F G E A C"
so "B" is first commom ancester of "D" and "F".
No comments:
Post a Comment