leetcode和算法----日更

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

2020-01-25  本文已影响0人  Arsenal4ever

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

直接写递归即可。

# 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
上一篇 下一篇

猜你喜欢

热点阅读