全部评论
这不是原题吗,还是BST,两道里面简单的那道
第一题咋做啊
力扣235
输入输出怎么写
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)
相关推荐
11-11 09:31
香港中文大学 后端 点赞 评论 收藏
分享