Why my python solution only passes 30/31 test cases? Any help here?

  • 0

    Very short recursion algorithm. I think it should be correct. But on the last test case it gave the wrong answer, not TLE.

    class Solution(object):
    def lowestCommonAncestor(self, root, p, q):
        Solution.node = None
        def dfs(root, p, q):
            if not root: return 0
                res = dfs(root.left,p,q)+dfs(root.right,p,q) + (root.val == p.val or root.val == q.val)
                if res == 2 and not Solution.node: 
                    Solution.node = root
                return res
        return Solution.node

    OK Now I get it, should change the mid line to

    (root == p or root == q)

    not comparing to the .val. Yes there could be duplicates here.

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.