剑指offer--面试题50:树中两个结点的最低公共祖先

来源:互联网 发布:网络推广属于什么岗位 编辑:程序博客网 时间:2024/05/01 08:39

1. 二叉排序树中求解两个结点的最低公共祖先

python实现:

# 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 lowestCommonAncestor(self, root, p, q):        """        :type root: TreeNode        :type p: TreeNode        :type q: TreeNode        :rtype: TreeNode        分析:二叉排序树,设p,q的最小公共祖先是r,那么应满足p.val<=r.val and q.val >=r.val,即p,q应在r的两侧        所以从根节点开始按照某种遍历搜索,检查当前节点是否满足这种关系,如果满足则返回。如果不满足,例如        p,q都大于r,那么继续搜索r的右子树        """        if root:            if root.val > p.val and root.val > q.val:                return self.lowestCommonAncestor(root.left, p, q)            elif root.val < p.val and root.val < q.val:                return self.lowestCommonAncestor(root.right, p, q)            else:                return root        return None


2.普通二叉树中求解两个结点的最低公共祖先

Python实现:

# 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 lowestCommonAncestor(self, root, p, q):        """        :type root: TreeNode        :type p: TreeNode        :type q: TreeNode        :rtype: TreeNode        """        if root is None or p is None or q is None:            return None        path1 = []        self.getPath(root, p, path1)        path2 = []        self.getPath(root, q, path2)        #if len(path1) == 0 or len(path2) == 0:        #    return None        result = None        for i in range(min(len(path1), len(path2))):            if path1[i] == path2[i]:                result = path1[i]        return result            def getPath(self, root, targetNode, path):        #当找到targetNode后,targetNode后面的节点就不再append        if len(path)>0 and path[-1] == targetNode:            return        if root:            path.append(root)            self.getPath(root.left, targetNode, path)            self.getPath(root.right, targetNode, path)            #如果还没有找到targetNode,就pop,不用担心路径上的点会pop掉,因为targetNode加入路径后,他路径上的祖先节点才会执行            #下面这个if判断(递归栈的顺序)            if len(path)>0 and path[-1] != targetNode:                path.pop()#######


0 0
原创粉丝点击