python 两个链表查找第一个公共子节点

157 阅读1分钟

题目1: 给定两个链表 A: a1,a2,c1,c2,c3 B:b1,b2,b3,b4,c1,c2,c3

   在节点c1处相交
   class solution:
       def getIntersectionNode(self,headA,headB):
             a,b = headA,headB
             while a != b:
                 if a:
                     a = a.next
                 elif a == None:
                     a = headB
                 if b:
                     b = b.next
                 elif b == None:
                     b = headA
             return a
             
         

题目2: 查找二茶树的最近公共祖先

     class solution():
         def func(root,p,q):
             if not root or root == p or root == q:
                 return root
             left = self.func(root.left,p,q)
             right = self.func(root.right,p,q)
             if not left and not right:
                 return 
             if not left:
                 return right 
             if not right:
                 return left
             return root