Skip to main content

Python Program to Find the Nearest Common Ancestor in the Given set of Nodes

Suppose we have a binary tree, so
the least common ancestor of the

i)               node 9 and node 6    =>    node 1

ii)              node 5 and node 9    =>    node 5

iii)            node 4 and node 6    =>    node 7

Definition of Nearest Common Ancestor

Let T be a binary tree. Let u and v be the nodes. The lowest common ancestor between two nodes u and v is defined as the lowest node In T that has both u and v as descendants. The Lca is the shared ancestor of u and v.


1.) If (node found)

       return node


       return Null

 2.) Traverse the nodes in Binary Tree using the inorder traversal i.e left -> parent ->   right node
      Again follow step 1

 3.) If the both node returns not null then it is the lowest common ancestor
      If at least one node returns Null then still we haven%u2019t got lowest common ancestor

The third point can be described using the below diagram:-

class Node: 
    def __init__(self,data): 
    #Assign data to the new node, set left and right children to None = data; 
        self.left = None; 
        self.right = None; 

def lowestCommonAncestor(root,n1,n2):        # Here, root represents the parent node

    # Step 1
    if(root is None):
        return None

    if( == n1 or
        return root

      # Step 2
    left = lowestCommonAncestor(root.left,n1,n2)
    right = lowestCommonAncestor(root.right,n1,n2)

     # Step 3 
    if left and right:     # Both nodes return some value, then we have got the lca [ where root is lca ]
        return root

     if left:                    # If one node returned NULL
         return left
         return right


root = Node(11); 
root.left = Node(12); 
root.right = Node(13); 
root.left.left = Node(14); 
root.left.right = Node(45); 
root.right.left = Node(64); 
root.right.right = Node(73);


Output :- 13

Popular posts from this blog

Introduction to Java Security

Introduction to Java Security The Java security architecture includes a large set of application programming interfaces (APIs), tools, and implementations of commonly-used security algorithms, mechanisms, and protocols. The Java security APIs span a wide range of areas. Cryptographic and public key infrastructure (PKI) interfaces provide the underlying basis for developing secure applications. Interfaces for performing authentication and access control enable applications to guard against unauthorized access to protected resources. The JDK includes a number of providers that implement a core set of security services. It also allows for additional custom providers to be installed. This enables developers to extend the platform with new security mechanisms. The JDK is divided into modules. Modules that contain security APIs include the following:

Module Description java.base Defines the foundational APIs of Java SE;  contained packages include,  and…

SQL Injection

Overview A SQL injection attack consists of insertion or "injection" of a SQL query via the input data from the client to the application. A successful SQL injection exploit can read sensitive data from the database, modify database data (Insert/Update/Delete), execute administration operations on the database (such as shutdown the DBMS), recover the content of a given file present on the DBMS file system and in some cases issue commands to the operating system. SQL injection attacks are a type of injection attack, in which SQL commands are injected into data-plane input in order to effect the execution of predefined SQL commands. Threat ModelingSQL injection attacks allow attackers to spoof identity, tamper with existing data, cause repudiation issues such as voiding transactions or changing balances, allow the complete disclosure of all data on the system, destroy the data or make it otherwise unavailable, and become administrators of the database server.SQL Injection is ve…

Insertion Node in the Linkelist.

In this post, methods to insert a new node in linked list are discussed. A node can be added in three ways
1) At the front of the linked list
2) After a given node.
3) At the end of the linked list
public class Linkedlist { Node head; class Node{ int data; Node next; Node(int d){ data =d; next=null; } } // INSERT THE NODE AT THE BEGIN OF LINKEDLIST. public void insertAtfront(int new_data){ // Node temp = head; Node new_node = new Node(new_data); = head; head = new_node; }  // INSERT THE NODE AT THE GIVEN POSITION IN LINKEDLIST.
public void insertAtGiven(Node prev_node,int new_data) { if(prev_node == null){ System.out.print("previous node can't be null"); return; } Node new_node = new Node(new_data); =; = new_node; } // INSERT THE NODE  AT THE END OF THE LINKEDLIST.   public void insertAtEnd(int new_data){ Node new_node = new Node(new_data); new_node.nex…