第一行输入两个整数 n 和 root,n 表示二叉树的总节点个数,root 表示二叉树的根节点。
以下 n 行每行三个整数 fa,lch,rch,表示 fa 的左儿子为 lch,右儿子为 rch。(如果 lch 为 0 则表示 fa 没有左儿子,rch同理)
最后一行为节点 o1 和 o2。
输出一个整数表示答案。
8 1 1 2 3 2 4 5 4 0 0 5 0 0 3 6 7 6 0 0 7 8 0 8 0 0 4 5
2
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p:int, q:int) -> 'TreeNode':
if not root&nbs***bsp;root.val == p&nbs***bsp;root.val == q:return root
left = self.lowestCommonAncestor(root.left, p, q)
right = self.lowestCommonAncestor(root.right, p, q)
if left and right:
return root
if left:return left
if right:return right
if __name__ == '__main__':
n, root_val = map(int, input().split())
node_key = {}
lst = []
for i in range(n):
v, l, r = map(int, input().split())
lst.append((v ,l, r))
node_key[v] = TreeNode(v)
if i == 0:root = node_key[v]
for v, l, r in lst:
if l:
node_key[v].left = node_key[l]
if r:
node_key[v].right = node_key[r]
p, q = map(int, input().split())
node = Solution().lowestCommonAncestor(root, p, q)
print(node.val)