leetcode之 Lowest Common Ancestor of a Binary Tree

来源:互联网 发布:第三波软件 编辑:程序博客网 时间:2024/06/02 04:58
这题是跟Lowest Common Ancestor of a Binary Search Tree相似的思路,不过不再是直接通过比较值来判定,而是要通过看在中序排序中的位置来定。极端的情况比如单链形式的q,p只相差1的情况会非常慢。特意加上了相差1的判定。代码如下:
# Definition for a binary tree node.# class TreeNode(object):#     def __init__(self, x):#         self.val = x#         self.left = None#         self.right = Noneclass Solution(object):    def __init__(self):        self.list1 = []    def inorder(self,root):        if root.left:            self.inorder(root.left)        self.list1.append(root)        if root.right:            self.inorder(root.right)    def lowestCommonAncestor(self, root, p, q):        """        :type root: TreeNode        :type p: TreeNode        :type q: TreeNode        :rtype: TreeNode        """        self.inorder(root)        self.indexofroot = self.list1.index(root)        self.indexofp = self.list1.index(p)        self.indexofq = self.list1.index(q)                def ancestor(root, p, q):            if self.indexofq <= self.indexofroot <= self.indexofp or self.indexofq >= self.indexofroot >= self.indexofp:                return root            if abs(self.indexofp - self.indexofq) == 1:                if p.left == q or p.right == q:                    return p                else:                    return p            elif self.indexofroot < self.indexofp and self.indexofroot < self.indexofq:                self.indexofroot = self.list1.index(root.right)                return ancestor(root.right, p, q)            else:                self.indexofroot = self.list1.index(root.left)                return ancestor(root.left, p, q)        return ancestor(root, p, q)

0 0