30 Day Risk-Free Guarantee:
100% money back if you're unsatisfied.
Book (308 Pages):
  • 150 Programming Interview Questions and Solutions
  • Five Proven Approaches to Solving Tough Algorithm Questions
  • Ten Mistakes Candidates Make -- And How to Avoid Them
  • Steps to Prepare for Behavioral and Technical Questions
  • Interview War Stories: A View from the Interviewer's Side
  • Book Preview and More Info

Video (One Hour):
  • Watch CareerCup's founder perform a totally unscripted technical interview of a candidate.
  • Overview of what interviewers look for in software engineering jobs.
  • Technical questions with white-boarding coding where the candidate does well - and struggles.
  • Interviewer reviews with what went well and poorly.
  • Video Preview and More Info

Resume Review (24 - 48hr)
  • Get your resume reviewed by a trained engineering interviewer. More Info
All Products / Services


Express Prep Package (Book)
$29.99 for e-book | $32.45 for paperback
Buy E-Book Buy on Amazon


Standard Prep Package (E-Book & Video)
Emailed Instantly | $39.99
Buy Standard

Elite Prep Package (E-Book, Video & Resume)
Emailed Instantly | $99.99
Buy Elite
 



Given 2 nodes in a binary tree, find their lowest common ancestor.

19


naga on November 14, 2009 |Edit | Edit

node *ancestor(node *start,node *m,node *n)
node *left,*right;
if(start==NULL)
return NULL;
if((start->left==m||start->left==n||start->right==m||start->right==n)){
printf("Entered\n");
return start;
}
else{

left=ancestor(start->left,m,n);
right=ancestor(start->right,m,n);
if(left!=NULL&&right!=NULL)
return start;
else { printf("NAGA\n");
return (left!=NULL?left:right);
}
}

}

Haripriya on November 14, 2009 |Edit | Edit

Node * findAncestor(Node * root,Node * node1, Node* node2)
{
if(root== NULL)
return NULL;
else if(node1->data == root->left->data && node2->data == root->right->data)
return root;
else if(node1->data< root->data && node2->data < root->data)
return findAncestor(root->left,Node * node1, Node* node2);
else if(node1->data > root->data && node2->data > root->data)
return findAncestor(root->right,Node * node1, Node* node2);
}

saurabhroongta2 on November 15, 2009 |Edit | Edit

Hi HariPriya,

I guess your solution will not work if node1 and node2 are not the immediate left and right(and vice versa) children of root.

But if they are not the immediate onces then their father's father shluld be searched.

Haripriya on November 14, 2009 |Edit | Edit

Sorry..Had put Node * node1 etc on the recursive call..

Node * findAncestor(Node * root,Node * node1, Node* node2)
{
if(root== NULL)
return NULL;
else if(node1->data == root->left->data && node2->data == root->right->data)
return root;
else if(node1->data< root->data && node2->data < root->data)
return findAncestor(root->left, node1, node2);
else if(node1->data > root->data && node2->data > root->data)
return findAncestor(root->right, node1, node2);
}

naga on November 14, 2009 |Edit | Edit

Hi Haripriya

I think this code doesnt work for all cases.
Suppose my tree is like 6
4 8
3 5
1
now i have to find least common ancestor for 1 5.Ur code will return NULL(ANS is 4),and problem is for a tree bt not for a binary search tree.Can u clarify if i made any mistake !!!!!!!!

saurabhroongta2 on November 15, 2009 |Edit | Edit

I think her solution will work if instead of "node1->data == root->left->data && node2->data == root->right->data" condition she will use "(node1->data < root->data && node2->data > root->data) || (node1->data > root->data && node2->data < root->data)"

karthik on November 14, 2009 |Edit | Edit

note that the question is for binary tree not a binary search tree

trey on November 14, 2009 |Edit | Edit

There is no no need for a recursive solution. Also, that should be a clarifying question, but I'm 100% sure the interviewer means a BST.

public class TreeNode<T> where T : IComparable<T>{
T Value {get; set;}
TreeNode<T> Left {get; set;}
TreeNode<T> Right {get; set;}
}

static TreeNode LowestCommonAncestor(TreeNode<T> Root, TreeNode<T> A, TreeNode<T> B)
{
if(Root == null || A == null || B == null)
throw new ArgumentNullException();
TreeNode<T> current = Root;
while(current != null){
int ADirection = A.Value.CompareTo(current.Value);
int BDirection = B.Value.CompareTo(current.Value);
if(ADirection == 0 || BDirection == 0 || ADirection != BDirection){
return current;
}
else{
if(Adirection < 0){
current = current.Left;
}
else{
current = current.Right;
}
}
}
return null
}

anon on November 15, 2009 |Edit | Edit

Why it has to be a BST? The solution for working with a BST is too straightforward.

Ankur on November 17, 2009 |Edit | Edit

I dnt understand wth is going on. The solution is so very simple. You just need find the node where the given two nodes split up in the left and right direction. Here is the pseudo code:


void traverse(node *root, int A, int B)
{
if(root == NULL)
return;
if(root->data > A && root->data > B)
traverse(root->left);
if(root->data < A && root->data < B)
traverse(root->right);
return root;
}

Anonymous on November 18, 2009 |Edit | Edit

dude , read the question again, its not a BST(which is easy), it could be a random binary tree, so checking for data wont work.

Ankur on November 18, 2009 |Edit | Edit

this is an SDET questions, its supposed to be easy. The question is incomplete. The exact same question is there in 'Programming interviews exposed' for a BST.

peace on November 22, 2009 |Edit | Edit

P.I.E. has solution for BST I suppose and not for binary tree. its been a while since I checked it. correct me if I am wrong.

Hari on January 15, 2010 |Edit | Edit

Just to clear the question posted....
the question asked was for binary trees. In fact, the interviewer said, there are parent pointers upwards and the other info (like left and right children weren't there).

Ashutosh on December 18, 2009 |Edit | Edit


I think the solution proposed till now only looking for immedeate child node
i.e.
root
/ \
node1 node2

But it wont looking for the scenario like:
root
/ \
node1 temp-node1
/ \
node2 temp-node2
In this scenario node1 & node2 are not the immedeate children of root.
But root is their lowest common ancestor.

Below is a solution that take care of all the scenarios:

struct Node;
// Temporary container, for tracking both node.
struct container
{
Node *node1;
Node *node2;
} ctnr;
Node * findAncestor(Node * root,Node * node1, Node* node2)
{
Node * left = 0;
Node * right = 0;
// root should not be null.
assert(root != 0);
// If its the node1, then store it in container
if(root == node1)
ctnr.node1 = node1;
// If its the node2, then store it in container
else if(root == node2)
ctnr.node2 = node2;
// Traverse left subtree
if(root->left)
left = findAncestor(root->left,node1,node2);
// Traverse right subtree
if(root->right)
right = findAncestor(root->right,node1,node2);
// If both already found in left subtree, then returning their immedeate ancestor node.
if(left != 0)
return left;
// If both already found in right subtree, then returning their immedeate ancestor node.
if(right != 0)
return right;
// Checking the marker in the container for both node's existance.
// If they found then return the root node.
if(ctnr.node1 != 0 && ctnr.node2 != 0)
return root;
// Default return is 0.
return 0;
}

predator on June 28, 2010 |Edit | Edit

Awesome solution Ashutosh@, nice thinking. This works completely, for almost all the cases that i can think off, and looks pretty straight-forward.

broadcaster on July 09, 2010 |Edit | Edit

For this we have to take the cntr as global ...!!

Anonymous on February 02, 2010 |Edit | Edit

bool LeastCommonAnscester(node *root, node *left, node *right, node **parent)
{
node *ans = *parent;
if(null == root)
{
return false;
}

bool found = false;
if(root == left || root == right)
{
found = true;
}

bool leftFound = LeastCommonAnscenter(root->left, left, right, &parent);
if(null != parent)
{
return true;
}
bool rightFound = LeastCommonAnscester(root->right, left, right, &parent);
if(null != parent)
{
return true;
}
if((leftFound && rightFound) || (leftFound || rightFound) && found))
{
ans = root;
return true;
}
else(((leftFound || rightFound) && !found) || ((!leftFound && !rightFound) && found)))
{

return true;
}

return false;

}

NKD on July 11, 2010 |Edit | Edit

typedef struct tree_node* tree_ptr;
struct tree_node
{
int k;
tree_ptr left;
tree_ptr right;
};

int search(tree_ptr node,int x)
{
if(node->data == x)
{
return 1;
}
return search(node->left,x);
return search(node->right,x);
}

tree_ptr commonanc(tree_ptr root,tree_ptr m, tree_ptr n)
{
if(root)
{
if(m->left == n || m->right == n)
return m;
if(n->left == m || n->right == m)
return n;
int n_l = search(root->left,n->k);
int n_r = search(root->right,n->k);
int m_l = search(root->left,m->k);
int m_r = search(root->right,m->k);
if((n_l && m_r)||(m_l&&n_r))
return root;
else if( n_l&&m_l)
return commonanc(root->left,n,m);
else
return commonnc(root->right,n,m);

}
return NULL;
}

Add a Text Comment | Add Runnable Code
Name:
Comment:

Writing Code? Surround your code with {{{ and }}} to preserve whitespace.








Amazon (1033)Bloomberg LP (403)Qualcomm (117)Adobe (88)Goldman Sachs (78)NetApp (49)IBM (43)Morgan Stanley (33)CapitalIQ (30)Sophos (25)Achieve Internet (23)Electronic Arts (19)Motorola (18)Research In Motion (17)Flipkart (16)
Microsoft (867)Google (141)NVIDIA (98)Yahoo (82)Epic Systems (69)Expedia (47)VMWare Inc (43)Apple (32)Cisco Systems (28)Facebook (23)Infosys (22)Agilent Technologies (19)Sage Software (17)Deshaw Inc (16)FlexTrade (15)
More Companies »
Software Engineer / Dev... (1062)Financial Software Deve... (170)Testing / Quality Assur... (56)Analyst (35)Virus Researcher (25)Field Sales (15)Developer Program Engin... (9)Front-end Software Engi... (6)MyJoB (5)area sales manager (4)Assistant (3)Cabin crew (2)Accountant (1)personnel (1)Intern (1)
Software Engineer in Te... (288)Program Manager (65)Development Support Eng... (47)INTERN(MSIDC) (28)Web Developer (18)System Administrator (10)Consultant (10)Production Engineer (5)Associate Technology L2 (5)AcquireKnowledge (4)Product Security Engine... (3)Solutions Architect (2)Gamer (1)mts (1)Fresh graduate interview (0)
More Job Titles »
Algorithm (1073)Terminology & Trivia (294)C (166)Object Oriented Design (159)Java (121)Testing (114)Arrays (101)Operating System (78)Database (70)Linked List (62)String Manipulation (56)Networking / Web / Inte... (44)Threads (36)Linux Kernel (33)PHP (22)
Coding (511)C++ (204)Behavioral (159)Data Structures (155)Experience (116)Brain Teasers (111)Computer Architecture &... (79)General Questions and C... (73)Trees and Graphs (69)Math & Computation (57)Application / UI Design (45)Ideas (38)System Design (35)Puzzles (30)Bit Manipulation (20)
More Topics »
CareerCup Official Interview Book Daily Questions Requests for Help Mock Interviews Video for Cracking the Coding Interview Job Placement Service CareerCup Blog
My Profile Edit Profile & Email Settings Sign Out