LeetCode 235. Lowest Common Ancestor of a Binary Search Tree
程序员文章站
2022-07-14 14:11:19
...
题目
思路
因为是BST,所以可以判断root和p、q的大小关系。
代码
# 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 not root or root == p or root == q: return root
if root.val < p.val and root.val < q.val: return self.lowestCommonAncestor(root.right, p, q)
if root.val > p.val and root.val > q.val: return self.lowestCommonAncestor(root.left, p, q)
return root
上一篇: 机器学习-随机森林回归(Random Forest Regression)
下一篇: LeetCode 235. Lowest Common Ancestor of a Binary Search Tree C++
推荐阅读
-
LeetCode 236 -- 二叉树的最近公共祖先 ( Lowest Common Ancestor of a Binary Tree ) ( C语言版 )
-
LeetCode 235--二叉搜索树的最近公共祖先 ( Lowest Common Ancestor of a Binary Search Tree ) ( C语言版 )
-
LeetCode 235. Lowest Common Ancestor of a Binary Search Tree 二叉搜索树
-
235. Lowest Common Ancestor of a Binary Search Tree
-
235. Lowest Common Ancestor of a Binary Search Tree
-
[Leetcode] 235. Lowest Common Ancestor of a Binary Search Tree
-
leetcode 235. Lowest Common Ancestor of a Binary Search Tree(二叉树的最低共同祖先)
-
LeetCode 235. Lowest Common Ancestor of a Binary Search Tree
-
LeetCode 235. Lowest Common Ancestor of a Binary Search Tree C++
-
Leetcode 235. Lowest Common Ancestor of a Binary Search Tree