美文网首页leetcode和算法----日更
leetcode 235 二叉搜索树的最近公共祖先

leetcode 235 二叉搜索树的最近公共祖先

作者: Arsenal4ever | 来源:发表于2020-01-25 22:52 被阅读0次

    这题重点是二叉搜索树!!!我把二叉树节点值特性忽略了,二叉树的左节点的值一定比它的根小,右节点的值一定比他的根值大。

    直接写递归即可。

    # Definition for a binary tree node.
    # class TreeNode(object):
    #     def __init__(self, x):
    #         self.val = x
    #         self.left = None
    #         self.right = None
    
    class Solution(object):
        def lowestCommonAncestor(self, root, p, q):
            """
            :type root: TreeNode
            :type p: TreeNode
            :type q: TreeNode
            :rtype: TreeNode
            """
            if p.val < root.val and q.val < root.val:
                return self.lowestCommonAncestor(root.left, p, q)
            if p.val > root.val and q.val > root.val:
                return self.lowestCommonAncestor(root.right, p, q)
            return root
    

    相关文章

      网友评论

        本文标题:leetcode 235 二叉搜索树的最近公共祖先

        本文链接:https://www.haomeiwen.com/subject/ztfdthtx.html