Finding the common ancestor in a binary tree

后端 未结 10 1064
悲哀的现实
悲哀的现实 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:34

    @Above, this will not work, because you are assuming that both nodes are immediate child of some particular node...

                8
         10           12
     7             
    

    and I gave the nodes as 7 and 12, answer must be 8. Lets do like this

        find(root, d1, d2, n1=null, n2=null)
         {
              if(n1 && n2) return;
              if(!root) return;
    
              else  if(root -> d == d1 ) n1 = root;
              else  if(root -> d == d2 ) n2 = root;                     
              find(root->left, d1, d2, n1, n2);
              find(root->right, d1, d2, n1, n2);
         }
    
         LCA(root, d1, d2)
         {
             node *n1=null, *n2=null;
             find(root, d1, d2, n1, n2);
             if(n1 == null || n2 == null )error 'nodes not present' exit(0);
             findIntersect(n1, n2); 
         }
         findInterSect(node *n1, node *n2)
         {
            l1 = length(n1);
            l2 = length(n2);
            node *g = n2, *l = n1;
            diff = abs(l1 - l2);
            if(l1>l2) g = n1 l =n2 
            while(diff) g = g->parent; diff--;
            // now both nodes are at same level
            while(g != l) g= g->parent, l = l->parent;
         }
    

提交回复
热议问题