全部评论
class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode': if p.val >q.val: p,q =q,p while True: if root.val>q.val: root = root.left elif root.val < p.val: root = root.right else: return root def create(ceng,tree): ln = [] for i in range(ceng): for j,c in enumerate(tree): if j<pow(2,i)-1 or j>pow(2,i+1)-2:continue tmp = TreeNode(c) ln.append(tmp) if j >0: if (j-1)/2==int((j-1)/2):ln[int((j-1)/2)].left = tmp if (j-1)/2>int((j-1)/2):ln[int((j-1)/2)].right = tmp return ln ceng = 4#int(input().strip()) tree = [int(i) for i in '9 6 15 2 -1 12 25 -1 -1 -1 -1 -1 -1 20 37'.strip().split()] son1,son2 = 12,20#[int(i) for i in input().strip().split()] root = create(ceng,tree) s = Solution() p = TreeNode(son1) q = TreeNode(son2) print(s.lowestCommonAncestor(root[0],p,q).val)
输入输出怎么写
力扣235
第一题咋做啊
这不是原题吗,还是BST,两道里面简单的那道
相关推荐
03-19 01:17
大连东软信息学院 人工智能
在打卡的大老虎很想潜...:你在找实习,没啥实习经历,技术栈放前面,项目多就分两页写,太紧凑了,项目你最多写两个,讲清楚就行,项目背景。用到的技术栈、亮点、难点如何解决,人工智能进面太难了,需求少。你可以加最新大模型的东西 点赞 评论 收藏
分享
点赞 评论 收藏
分享
