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)            
点赞 3

相关推荐

不要停下啊:大二打开牛客,你有机会开卷了,卷起来,去找课程学习,在牛客上看看大家面试笔试都需要会什么,岗位有什么需求就去学什么,努力的人就一定会有收获,这句话从来都经得起考验,像我现在大三了啥也不会,被迫强行考研,炼狱难度开局,啥也不会,找工作没希望了,考研有丝丝机会
点赞 评论 收藏
分享
牛客网
牛客网在线编程
牛客网题解
牛客企业服务