Finding the common ancestor in a binary tree

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

    hi this will return lowest ancestor node value where root of tree and val1,val2 -> data values for nodes are being passed

    int CommonAncestor(node *root, int val1,int val2) 
    {
    
        if(root == NULL || (! root->left && ! root->right  )
            return false;
    
            while(root)
            {
                if(root->data < val1 && root->data < val2)
                 {
                    root = root->left;
                 }
                 else if(root->data > val1 && root->data > val2)
                {
                    root= root->right;
                }
                else
                  return root->data;      
            }
    }
    

提交回复
热议问题