AcWing 88. 树中两个结点的最低公共祖先
原题链接
中等
作者:
adamXu
,
2020-10-03 09:06:21
,
所有人可见
,
阅读 368
/**
* 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) {
//树嘛,得想到递归,lowestCommonAncestor函数实现的功能是找到两个节点的公共
//父节点,如果未找到则返回本身
if(!root) return nullptr;
if(root == p || root == q) return root;
auto left = lowestCommonAncestor(root->left,p,q);
auto right = lowestCommonAncestor(root->right,p,q);
if(left && right) return root; //如果两边都有公共节点,说明两边都是他本身,返回root
if(right) return right; //如果只有一边有则返回那一边即可
return left;
}
};