Iam_Sandeep

Least common ancestor LCA

Mar 22nd, 2022 (edited)
208
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.97 KB | None | 0 0
  1. #User function Template for python3
  2. link="https://practice.geeksforgeeks.org/problems/lowest-common-ancestor-in-a-binary-tree/1#"
  3. '''
  4. class Node:
  5.    def __init__(self, value):
  6.        self.left = None
  7.        self.data = value
  8.        self.right = None
  9. '''
  10.  
  11. class Solution:
  12.     #Function to return the lowest common ancestor in a Binary Tree.
  13.     def lca(self,root, n1, n2):
  14.         ans=[None]
  15.         def dfs(x):
  16.             if not x:return 0,0
  17.             else:
  18.                 a,b=None,None
  19.                 m,n=dfs(x.left)
  20.                 p,q=dfs(x.right)
  21.                
  22.                 s=m or p or x.data==n1#checks whether have we have visited n1
  23.                 t=n or q or x.data==n2#checks whether have we visited n2
  24.                
  25.                 if s and t:
  26.                     if ans[0]==None:
  27.                         ans[0]=x
  28.                 return s,t
  29.         dfs(root)
  30.         return ans[0]
  31.  
  32.  
  33.  
  34. #{
  35. #  Driver Code Starts
  36. #Initial Template for Python 3
  37.  
  38. #Contributed by Sudarshan Sharma
  39. from collections import deque
  40. # Tree Node
  41. class Node:
  42.     def __init__(self, val):
  43.         self.right = None
  44.         self.data = val
  45.         self.left = None
  46.  
  47.  
  48.  
  49. # Function to Build Tree  
  50. def buildTree(s):
  51.     #Corner Case
  52.     if(len(s)==0 or s[0]=="N"):          
  53.         return None
  54.        
  55.     # Creating list of strings from input
  56.     # string after spliting by space
  57.     ip=list(map(str,s.split()))
  58.    
  59.     # Create the root of the tree
  60.     root=Node(int(ip[0]))                    
  61.     size=0
  62.     q=deque()
  63.    
  64.     # Push the root to the queue
  65.     q.append(root)                            
  66.     size=size+1
  67.    
  68.     # Starting from the second element
  69.     i=1                                      
  70.     while(size>0 and i<len(ip)):
  71.         # Get and remove the front of the queue
  72.         currNode=q[0]
  73.         q.popleft()
  74.         size=size-1
  75.        
  76.         # Get the current node's value from the string
  77.         currVal=ip[i]
  78.        
  79.         # If the left child is not null
  80.         if(currVal!="N"):
  81.            
  82.             # Create the left child for the current node
  83.             currNode.left=Node(int(currVal))
  84.            
  85.             # Push it to the queue
  86.             q.append(currNode.left)
  87.             size=size+1
  88.         # For the right child
  89.         i=i+1
  90.         if(i>=len(ip)):
  91.             break
  92.         currVal=ip[i]
  93.        
  94.         # If the right child is not null
  95.         if(currVal!="N"):
  96.            
  97.             # Create the right child for the current node
  98.             currNode.right=Node(int(currVal))
  99.            
  100.             # Push it to the queue
  101.             q.append(currNode.right)
  102.             size=size+1
  103.         i=i+1
  104.     return root
  105.    
  106.    
  107. if __name__=="__main__":
  108.     t=int(input())
  109.     for _ in range(0,t):
  110.         a,b=list(map(int,input().split()))
  111.         s=input()
  112.         root=buildTree(s)
  113.         k=Solution().lca(root,a,b)
  114.         print(k.data)
  115.  
  116.  
  117.  
  118. # } Driver Code Ends
Add Comment
Please, Sign In to add comment