class TreeNode:
def __init__(self, value=0, left=None, right=None):
self.value = value
self.left = left
self.right = right
def parent(root,p,q):
if root == p or root == q:
return root
left,right = None,None
if root.left:
left = parent(root.left,p,q)
if root.right:
right = parent(root.right,p,q)
if left and right:
return root
elif left:
return left
elif right:
return right
def distance(root,node):
queue = [[root,0]]
while queue:
temp,dis = queue.pop(0)
if temp == node:
return dis
else:
if temp.left:
queue.append([temp.left,dis+1])
if temp.right:
queue.append([temp.right,dis+1])
root = TreeNode(1)
root.left = TreeNode(2)
root.right = TreeNode(3)
root.left.left = TreeNode(4)
root.left.right = TreeNode(5)
root.right.right = TreeNode(6)
root.left.right.left = TreeNode(7)
p = root.left.right.left # 节点 7
q = root # 节点 1
parent_node = parent(root,p,q)
dis_1 = distance(parent_node,p)
dis_2 = distance(parent_node,q)
print(dis_1 + dis_2)
标签:right,TreeNode,parent,Python,二叉树,dis,root,节点,left
From: https://www.cnblogs.com/DCFV/p/18442779