Leetcode 236.二叉树的最低共同祖先?

时间:2018-10-25 20:07:06

标签: python-3.x iteration binary-search-tree depth-first-search

关于此问题,我遇到了一些问题。以下是原始问题:

enter image description here

我决定使用堆栈来存储跟踪,然后从左子树到右子树进行DFS。
在此过程中,当找到q或p时,只需将迹线推入新的堆栈(stack1)。第二次找到其余的q或p时,可以检查stack1的长度是否为2,因此我们中断迭代并比较两条迹线以找到答案。

完成后,我运行了一些自定义测试用例,它们都正常工作。但是提交后,系统显示“运行时错误”。有人可以帮我弄清楚为什么我错了吗?任何意见或建议将不胜感激。谢谢。

这是我的原始答案:

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

from copy import deepcopy
class Solution(object):
    def lowestCommonAncestor(self, root, p, q):
        """
        :type root: TreeNode
        :type p: TreeNode
        :type q: TreeNode
        :rtype: TreeNode
        """
        stack1, stack, last, sign = [], [], root, False
        stack.append(root)
        if root == q or root == p:
            stack1.append([root])

        while stack:
            while root.left and root.left != last and root.right != last:
                last = root
                root = root.left
                stack.append(root)
                if root == p or root == q:
                    stack1.append(deepcopy(stack))
                    if len(stack1) == 2:
                        sign = True
                        break
            if sign:
                break

            if root.right != last and root.right:
                ast = root
                root = root.right
                stack.append(root)
                if root == p or root == q:
                    stack1.append(deepcopy(stack))
                    if len(stack1) == 2:
                        break
            else:
                last = stack.pop()
                root = stack[-1]

        for x in stack1[0][::-1]:
            for y in stack1[1][::-1]:
                if y.val == x.val:
                    return x

0 个答案:

没有答案
相关问题