关闭

Easy-题目14:235.Lowest Common Ancestor of a Binary Search Tree

116人阅读 评论(0) 收藏 举报
分类:

题目原文:
Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BST.

According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes v and w as the lowest node in T that has both v and w as descendants (where we allow a node to be a descendant of itself).”

    _______6______
   /              \
___2__          ___8__

/ \ / \
0 _4 7 9
/ \
3 5
For example, the lowest common ancestor (LCA) of nodes 2 and 8 is 6. Another example is LCA of nodes 2 and 4 is 2, since a node can be a descendant of itself according to the LCA definition.
题目大意:
给出一个二叉排序树,求两个节点的最近公共祖先。(一个节点的祖先也可以是自己)
题目分析:
(1) 空节点的祖先是空;
(2) 若当前根节点的值比两个节点的值都大,则公共祖先在左子树里,递归向左子树搜索;
(3) 若当前根节点的值比两个节点的值都小,则公共祖先在右子树里,递归向右子树搜索;
(4) 上述情况均不成立,则当前节点就是公共祖先。
源码:(language:c)

struct TreeNode* lowestCommonAncestor(struct TreeNode* root, struct TreeNode* p, struct TreeNode* q) {
    if (!root || !p || !q)           
        return NULL;
    else if (root->val < p->val && root->val < q->val)
        return lowestCommonAncestor(root->right, p, q);
    else if (root->val > p->val && root->val > q->val)
        return lowestCommonAncestor(root->left, p, q);
    else
        return root;        
}

成绩:
24ms,beats 22.03%,众数24ms,77.40%
Cmershen的碎碎念:
注意利用二叉排序树的定义的性质。总结如下:
二叉排序树或者是一棵空树,或者是具有下列性质的二叉树:
(1)若左子树不空,则左子树上所有结点的值均小于它的根结点的值;
(2)若右子树不空,则右子树上所有结点的值均大于它的根结点的值;
(3)左、右子树也分别为二叉排序树;
(4)没有键值相等的节点。
性质:二叉排序树的中序遍历是递增序列。

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:55990次
    • 积分:3198
    • 等级:
    • 排名:第10679名
    • 原创:270篇
    • 转载:53篇
    • 译文:0篇
    • 评论:7条
    文章分类
    最新评论