0
votes

I wrote a code for Lowest Common Ancestor of a Binary Tree search.

class TreeNode:
    def __init__ (self, x):
        self.val = x
        self.right = None
        self.left = None

class Solution:
    def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
        if not root:
            return None
        elif root == p or root == q:
            return root
    
        l = self.lowestCommonAncestor(root.left, p, q)
        r = self.lowestCommonAncestor(root.right, p, q)
    
        if l and r:
            return root
        else:
            return l or r

However, when I try to call out the method for LCA -

s = Solution()
s.lowestCommonAncestor([3,5,1,6,2,0,8,None,None,7,4],5,1)

it gives me this:

AttributeError: 'list' object has no attribute 'left'
can you fix the indentation? - Hugh Mungus
The identation is not a problem. But, thanks! I did make a styling flaw when I posted the question. - Qagan
Going off your type hinting, you should be giving a TreeNode instance not a list to lowestCommonAncestor so it should be s.lowestCommonAncestor(TreeNode([3,5,1,6,2,0,8,None,None,7,4]),TreeNode(5),TreeNode(1)) but this returns None - Hugh Mungus