码迷,mamicode.com
首页 > 其他好文 > 详细

二叉树(3)

时间:2020-04-24 11:42:55      阅读:55      评论:0      收藏:0      [点我收藏+]

标签:遍历   roo   turn   val   lse   pre   ret   __init__   else   

技术图片

 

 

 

 

# Definition for a binary tree node.
# 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 not root:
            return 
        if root.val > p.val and root.val >q.val:
            return self.lowestCommonAncestor(root.left,p,q)
        if root.val < p.val and root.val < q.val:
            return self.lowestCommonAncestor(root.right,p,q)
        return root


        

 

 

class Solution:
    def lowestCommonAncestor(self, root: TreeNode, p: TreeNode, q: TreeNode) -> TreeNode:
        if p.val > q.val: p, q = q, p # 保证 p.val < q.val
        while root:
            if root.val < p.val: # p,q 都在 root 的右子树中
                root = root.right # 遍历至右子节点
            elif root.val > q.val: # p,q 都在 root 的左子树中
                root = root.left # 遍历至左子节点
            else: break
        return root

 

二叉树(3)

标签:遍历   roo   turn   val   lse   pre   ret   __init__   else   

原文地址:https://www.cnblogs.com/topass123/p/12766272.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!