两个节点之间的祖先

时间:2017-09-09 16:20:46

标签: python algorithm data-structures binary-search-tree

我有一个关于如何在二叉搜索树上找到两个节点之间最不共同的祖先的问题。这是来自我的项目,我做了以下但是审阅者希望我实现有效的解决方案,而无需创建树并在其中添加节点。我的意思是我需要做些什么才能修复我的代码?

root = None

Class Node:
    #Constructor to create a new node
    def __init__(self, data):
        self.data = data
        self.left = None
        self.right = None

    # Function to insert a new node at the beginning
    def insert_right(node, new_data):
        new_node = Node(new_data)
        node.right = new_node
        return new_node

    # Function to insert a new node at the beginning
    def insert_left(node, new_data):
        new_node = Node(new_data)
        node.left = new_node
        return new_node    

    # Function to find least common ancestor
    def lca(root, n1, n2):

        # Base case
        if root is None:
            return None

        # If both n1 and n2 are smaller than root,
        # then LCA lies on left
        if(root.data > n1 and root.data > n2):
            return lca(root.left, n1, n2)

        # if both n1 and n2 are greater than root,
        # then LCA lies on right
        if(root.data < n1 and root.data < n2):
            return lca(root.right, n1, n2) 

        return root.data

    def question4(the_matrix, the_root, n1, n2):
        global root
        root = Node(the_root)
        root.left, root.right = None, None
        node_value = 0
        tmp_right, tmp_left = None, None
        node_list = []
        for elem in the_matrix[the_root]:
            if elem:
                if(node_value>the_root):
                    node_list.append(push_right(root, node_value))
                else:
                    node_list.append(push_left(root, node_value))
            node_value += 1

        tmp_node = node_list.pop(0)
        while tmp_node != None:
            node_value = 0
            for elem in the_matrix[tmp_node.data]:
                if elem:
                    if(node_value>tmp_node.data):
                        node_list.append(push_right(tmp_node, node_value))
                    else:
                        node_list.append(push_left(tmp_node, node_value))
                node_value += 1
            if node_list == []:
                break
            else:
                tmp_node = node_list.pop(0)

        return lca(root, n1, n2)  

def main():
    global root    
    print question4([[0, 0, 0, 0, 0],
                     [1, 0, 1, 0, 0],
                     [0, 0, 0, 0, 0],
                     [0, 1, 0, 0, 1],
                     [0, 0, 0, 0, 0]],3, 1, 2)

if __name__ == '__main__':
    main()

1 个答案:

答案 0 :(得分:0)

审稿人希望您直接使用矩阵表示来查找LCA,而不是在您定义的树结构上实现lca

基本上,不要使用Node类,只需使用矩阵行来理解节点关系。