[英]Ancestor between two nodes
我有一个问题,如何找到二叉搜索树上两个节点之间的最小公祖。 这是从我的项目中获得的,我执行了以下操作,但是审阅者希望我在不创建树并将节点添加到其中的情况下实现有效的解决方案。 我的意思是我需要做些什么来修复我的代码?
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()
审阅者希望您不直接在所定义的树结构上实现lca
,而是直接使用矩阵表示形式来查找LCA。
基本上,不要使用Node
类,只需使用矩阵行来了解节点关系。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.