LeetCode Lowest Common Ancestor of a Binary Search Tree (LCA最近公共祖先)

时间:2023-03-09 07:45:55
LeetCode Lowest Common Ancestor of a Binary Search Tree (LCA最近公共祖先)

题意:

  给一棵二叉排序树,找p和q的LCA。

思路:

  给的是BST(无相同节点),那么每个节点肯定大于左子树中的最大,小于右子树种的最小。根据这个特性,找LCA就简单多了。

  分三种情况:

  (1)p和q都在root左边,那么往root左子树递归。

  (2)在右同理。

  (3)一左一右的,那么root->val肯定大于其中的1个,小于另一个。

 /**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { //这是一棵排序树啊!
if( (root->val - p->val ) * (root->val - q->val) <= ) //一大一小必会产生负的,或者root为其中1个,那么就是0
return root;
if( max(p->val, q->val) < root->val ) //都在左边
return lowestCommonAncestor(root->left, p, q);
else //都在右边
return lowestCommonAncestor(root->right, p, q);
}
};

AC代码

python3

  迭代

 class Solution(object):
def lowestCommonAncestor(self, root, p, q):
"""
:type root: TreeNode
:type p: TreeNode
:type q: TreeNode
:rtype: TreeNode
"""
while root:
if (p.val-root.val)*(q.val-root.val)<=0: #一左一右
return root
elif p.val<root.val: #左
root=root.left
else:
root=root.right

AC代码

  递归

 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)*(q.val-root.val)<=0: #一左一右
return root
elif p.val<root.val: #左
return self.lowestCommonAncestor(root.left, p, q)
else:
return self.lowestCommonAncestor(root.right, p, q)

AC代码