题解 | #农场牛群族谱# 递归解法
农场牛群族谱
https://www.nowcoder.com/practice/7d28855a76784927b956baebeda31dc8
知识点
递归 最近公共祖先
思路
要找两个点的最近公共祖先,从根节点查找所在的子树中是否含有这两个值,假如左右子树都含有目标节点,说明它们分居两个子树中,答案是当前父节点;假如有一个子树不存在,说明两个都在另外一个子树中。
时间复杂度
遍历一遍二叉树
AC code(C++)
/**
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* };
*/
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param root TreeNode类
* @param p int整型
* @param q int整型
* @return int整型
*/
int lowestCommonAncestor(TreeNode* root, int p, int q) {
if (!root) return -1;
if (root->val == p or root->val == q) return root->val;
auto l = lowestCommonAncestor(root->left, p, q);
auto r = lowestCommonAncestor(root->right, p, q);
if (l >= 0 and r >= 0) return root->val;
return l == -1 ? r : l;
}
};