Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Created linked_list_is_palindrome #453

Merged
merged 2 commits into from Dec 15, 2020
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Create Least_Common_Ancestor.cpp
  • Loading branch information
atendstowards0 committed Oct 1, 2020
commit 8c568251e7ad8b2171391e5c8bae232d4a67fd01
59 changes: 59 additions & 0 deletions Trees/Least_Common_Ancestor.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
// A recursive CPP program to find Least Common Ancestor of two nodes n1 and n2.
#include <bits/stdc++.h>
using namespace std;

class node
{
public:
int data;
node* left, *right;
};

// Function to find LCA of n1 and n2. The function assumes that both n1 and n2 are present in BST
node *lca(node* root, int n1, int n2)
{
if (root == NULL) return NULL;

// If both n1 and n2 are smaller than root, then LCA lies in left
if (root->data > n1 && root->data > n2)
return lca(root->left, n1, n2);

// If both n1 and n2 are greater than root, then LCA lies in right
if (root->data < n1 && root->data < n2)
return lca(root->right, n1, n2);

return root;
}

// function that allocates a new node with the given data.
node* newNode(int data)
{
node* Node = new node();
Node->data = data;
Node->left = Node->right = NULL;
return(Node);
}

int main()
{
node *root = newNode(20);
root->left = newNode(8);
root->right = newNode(22);
root->left->left = newNode(4);
root->left->right = newNode(12);
root->left->right->left = newNode(10);
root->left->right->right = newNode(14);

int n1 = 10, n2 = 14;
node *t = lca(root, n1, n2);
cout << "LCA of " << n1 << " and " << n2 << " is " << t->data<<endl;

n1 = 14, n2 = 8;
t = lca(root, n1, n2);
cout<<"LCA of " << n1 << " and " << n2 << " is " << t->data << endl;

n1 = 10, n2 = 22;
t = lca(root, n1, n2);
cout << "LCA of " << n1 << " and " << n2 << " is " << t->data << endl;
return 0;
}