五. 二叉树 1 Lowest Common Ancestor

思路:

  1. 自上而下
    分别找出A,B的路径,然后寻找最短相同部分,最后一个node就是LCA。
    (未经测试)
def lowestCommonAncestor(self, root, A, B):
        # write your code here
        path = []
        self.final = []
        path.append(root)
        
        def dfs(root, target, path):
            if root.left == None and root.right == None:
                return
            if root.left:
                if root.left == target:
                    path.append(target)
                    self.final = path
                    return
                else:
                    path.append(root.left)
                    dfs(root.left, target, path)
                    
            if root.right:
                path.pop()
                if root.right == target:
                    path.append(target)
                    return
                else:
                    path.append(root.left)
                    dfs(root.left, target, path)
                    
        dfs(root, A, path)
        path_A = self.final 
        dfs(root, B, path)
        path_B = self.final
        
        for i in range(0,len(path_B)):
            if path_A[:i] != path_B[:i]:
                return path_A[i-1]
  1. 自下而上
    A,B 两个点一定在LCA的两个分支里,或者一个点在另一个点的分枝里。
"""
Definition of TreeNode:
class TreeNode:
    def __init__(self, val):
        self.val = val
        self.left, self.right = None, None
"""


class Solution:
    """
    @param: root: The root of the binary search tree.
    @param: A: A TreeNode in a Binary.
    @param: B: A TreeNode in a Binary.
    @return: Return the least common ancestor(LCA) of the two nodes.
    """
    def lowestCommonAncestor(self, root, A, B):
        # write your code here
        if root == None or root == A or root == B:
            return root
        left = self.lowestCommonAncestor(root.left, A, B)
        right = self.lowestCommonAncestor(root.right, A, B)
        
        if left and right:
            return root
        else:
            if left:
                return left
            else:
                 return right
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容