#### Tree Search - given two nodes in a tree, check if they are connected - python

``````"1"
└ "2"
├ "2.1"
┊   └ "3"
┊
└ "2.2"
└ "2.2.1"
└ "3"
``````

``````a="3"      b="1"    -> False
a="3"      b="2"    -> False
a="2.2.1"  b="2.2"  -> True
a="2.2.1"  b="3"    -> True
``````

2 个回复

``````tree = {'name': '1', 'children': [{'name': '2', 'children': [{'name': '2.1', 'children': [{'name': '3'}]}, {'name': '2.2', 'children': [{'name': '2.2.1', 'children': [{'name': '3'}]}]}]}]}
def in_tree(d, node):
return d['name'] == node or any(in_tree(i, node) for i in d.get('children', []))

def lookup(tree, a, b, flag=False):
if tree['name'] == b and flag:
return True
return any(lookup(j, a, b, tree['name'] == a) for j in tree.get('children', []))

test = [['3', '1'], ['3', '2'], ['2.2.1', '2.2'], ['2.2.1', '3'], ['60', '70']]
for a, b in test:
if not in_tree(tree, a) or not in_tree(tree, b):
raise AttributeError('Node(s) missing in tree')
print(any([lookup(tree, a, b), lookup(tree, b, a)]))
``````

``````False
False
True
True
Traceback (most recent call last):
File "<stdin>", line 3, in <module>
AttributeError: Node(s) missing in tree
``````

``````from anytree import Node, RenderTree

nodes = {} # a dict as a lookup to find nodes by name

if parentval is not None:
node = nodes[val] = Node(val, parent=nodes[parentval])
else:
node = nodes[val] = Node(val)
return node

def mk_tree():

def is_child_or_parent(n1, n2):
return n1.parent == n2 or n2.parent == n1

testpatterns = [
("3", "1", False),
("3", "2", False),
("2.2.1", "2.2", True),
("2.2.1", "3", True),
]

def run_test():
for name1, name2, expected in testpatterns:
node1 = nodes[name1]
node2 = nodes[name2]
rslt = is_child_or_parent(node1, node2)
print(node1, node2, expected, rslt)
assert rslt == expected

tree = mk_tree()
print(RenderTree(tree))
run_test()
``````
1 检查树中的节点是否已删除

2 在树中检查给定节点是否是另一个节点的祖先

5 检查两个树的颜色是否相等

7 检查是python中的树是二叉搜索树

8 未加权图/树中两个给定节点之间的最短路径

9 连接树中的节点