05_二叉树的最近公共祖先

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


# 之前用的递归 但是发现需要的值在最底层 无法返回上来
# 一想 既然在最底层 那就用循环 最后一个值不就是需要的结果吗
# 只改了最后两个 self.lowestCommonAncestor 的递归调用 给root重新赋值 结果竟然正确
# 单个结果没问题 但是测试遇到超时 不通过
class Solution(object):
    def lowestCommonAncestor(self, root, p, q):
        """
        :type root: TreeNode
        # :type p: TreeNode
        # :type q: TreeNode
        :rtype: TreeNode
        解题思路:p q节点在root两边 则最近公共节点就是根节点
        在一边:如果p 或 q 其中之一就是root节点 则root就是最近公共节点
               否则 root 重新赋值为 root.left 或 root.right 继续下一循环
        """
        if not root:
            return

        p, q = p.val, q.val

        while root:
            # 中序遍历
            def z(node):
                if not node:
                    return []
                left = z(node.left)
                right = z(node.right)
                return left + [node.val] + right

            # 后序遍历
            def h(node):
                if not node:
                    return []
                left = h(node.left)
                right = h(node.right)
                return left + right + [node.val]

            list_z = z(root)
            list_h = h(root)
            print(list_z, list_h)

            # 根节点在中序遍历中的位置
            root_index = list_z.index(list_h[-1])
            p_index = list_z.index(p)
            q_index = list_z.index(q)

            if p_index > root_index > q_index or p_index < root_index < q_index:
                return root
            elif p == root.val or q == root.val:
                print(root.val)
                return root
            else:
                # 都在左边
                if p_index < root_index:
                    # self.lowestCommonAncestor(root.left, p, q)
                    root = root.left
                # 都在右边
                else:
                    # self.lowestCommonAncestor(root.right, p, q)
                    root = root.right


a = TreeNode(3)
b = TreeNode(5)
c = TreeNode(1)
d = TreeNode(6)
e = TreeNode(2)
f = TreeNode(0)
g = TreeNode(8)
h = TreeNode(7)
i = TreeNode(4)

a.left, a.right = b, c
c.left, c.right = f, g
b.left, b.right = d, e
e.left, e.right = h, i

s = Solution()
print(s.lowestCommonAncestor(a, b, c))


你可能感兴趣的:(05_二叉树的最近公共祖先)