60-Lowest Common Ancestor of a Binary Search Tree
2024-09-05 05:52:18
- Lowest Common Ancestor of a Binary Search Tree My Submissions QuestionEditorial Solution
Total Accepted: 68335 Total Submissions: 181124 Difficulty: Easy
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.
本题是BST,是二叉查找树
针对二叉查找树BST的情况
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
assert(p!=NULL&&q!=NULL);
if(root==NULL) return NULL;
if(max(p->val, q->val) < root->val)
return lowestCommonAncestor(root->left, p, q);
else if(min(p->val, q->val) > root->val)
return lowestCommonAncestor(root->right, p, q);
else return root;
}
};
针对一般的树有以下解决方法:
思路:
判定是否根,是的话返回根,不是
判定p,q的分布,如下:
/**
* 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) {
assert(p!=NULL&&q!=NULL); //默认p,q不为空,否则为空的不知归为哪个节点
if(root==NULL)return NULL;
if(root==p||root==q)return root;
TreeNode *tmp;
bool right_p=inTheTree(root->right,p),left_p = inTheTree(root->left,p);
bool right_q=inTheTree(root->right,q),left_q = inTheTree(root->left,q);
if((right_p&&left_q)||(right_q&&left_p))return root; //分别在左右子树,返回根
if(right_p&&right_q)return lowestCommonAncestor(root->right,p,q);//全在右子树,转化为根为右节点的子问题
if(left_p&&left_q)return lowestCommonAncestor(root->left,p,q);//全在左子树,转化为根为右节点的子问题
return tmp;
}
bool inTheTree(TreeNode* head, TreeNode* p)//判定p是否在树中
{
if(head==NULL||p==NULL)return false;
if(head==p)return true;
else return inTheTree(head->left,p)||inTheTree(head->right,p);
}
};
最新文章
- jQuery源码笔记(二):定义了一些变量和函数 jQuery = function(){}
- 磁盘文件系统Fat、Fat32、NTFS、exFAT的优缺点
- 【转】JSP使用上传文件,并生产高清缩略图示例
- iOS开发UI篇—IOS开发中Xcode的一些使用技巧
- 【转】notepad++ 应用学习 -- 列模式,十六进制模式
- SpringMVC入门1
- MySQL批量更新死锁案例分析--转载
- mysql外键设置选项
- buildah---github简单记录
- Monolog手册参考
- 发现一个好玩的东西 Web Scraper
- Codeforces 984 D - XOR-pyramid
- Study From DevOps 学习交流会议
- loopback v4 特性
- Vue如何使用动态刷新Echarts组件
- htaccess文件中RewriteRule 规则参数介绍
- Git--时光穿梭机之删除文件06
- 泛型举例:List<;T>;与DateTable相互转换
- “RPC好,还是RESTful好?”
- ANSI与Unicode的转换