美文网首页
Leetcode-236题:Lowest Common Ance

Leetcode-236题:Lowest Common Ance

作者: 八刀一闪 | 来源:发表于2016-10-08 22:14 被阅读23次

    题目

    Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree.

    思路

    分别求出跟节点到p,q的路径,那么路径的共同前缀的末尾即为所求。

    代码

    # Definition for a binary tree node.
    # class TreeNode(object):
    #     def __init__(self, x):
    #         self.val = x
    #         self.left = None
    #         self.right = None
    
    class Solution(object):
    
        def visit(self, root, cur_path, pathes, p, q):
            if root == None:
                return
            cur_path.append(root)
            if root==p:
                pathes.append(cur_path[:])
            if root==q:
                pathes.append(cur_path[:])
            self.visit(root.left, cur_path, pathes, p, q)
            self.visit(root.right, cur_path, pathes, p, q)
            cur_path.pop()
    
        def lowestCommonAncestor(self, root, p, q):
            """
            :type root: TreeNode
            :type p: TreeNode
            :type q: TreeNode
            :rtype: TreeNode
            """
            if root == None:
                return None
            pathes = []
            self.visit(root, [], pathes, p, q)
            i = 0
            while i < min(len(pathes[0]),len(pathes[1])):
                if pathes[0][i] != pathes[1][i]:
                    break
                i += 1
            return pathes[0][i-1]
    

    相关文章

      网友评论

          本文标题:Leetcode-236题:Lowest Common Ance

          本文链接:https://www.haomeiwen.com/subject/ylcpyttx.html