最近公共祖先

# 找两个节点的最近的公共祖先
# 假设两个节点 node1 和 node2,那么最近公共祖先和node1、node2存在以下关系:
# 1、node1,node2分别在祖先左右两侧
# 2、祖先是node1,node2在祖先左/右侧
# 3、祖先是node2,node1在祖先左/右侧
# 使用dfs深度优先遍历进行求解
# 定义一颗二叉树


class TreeNode:
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None
# 根据list创建二叉树


def listcreattree(root, llist, i):
    if i < len(llist):
        if llist[i] == '#':
            return None
        else:
            root = TreeNode(llist[i])
            root.left = listcreattree(root.left, llist, 2 * i + 1)
            root.right = listcreattree(root.right, llist, 2 * i + 2)
            return root
    return root


class Solution:
    def nearest_common_ancestor(self, root, node1, node2):
        if not root:
            return None
        if root.val == node1 or root.val == node2:
            return root.val
        left = self.nearest_common_ancestor(root.left, node1, node2)
        right = self.nearest_common_ancestor(root.right, node1, node2)
        if left is not None and right is not None:
            return root.val
        if left is None:
            return right
        if right is None:
            return left
        return None


if __name__ == '__main__':
    test_list = [3, 5, 1, 6, 2, 0, 8, '#', '#', 7, 4]
    root = listcreattree(None, test_list, 0)
    tmp1 = Solution()
    print(tmp1.nearest_common_ancestor(root, 5, 1))
# 结果为 3

posted @ 2020-12-29 19:47  0-1-world  阅读(91)  评论(0编辑  收藏  举报