236. 二叉树的最近公共祖先 - 力扣(LeetCode)
递归
lson、rson左右子树;
深度优先遍历,遍历到p或者q就返回ture;
class Solution {
public:
TreeNode* ans;
bool dfs(TreeNode* root, TreeNode* p, TreeNode* q)
{
if(root == nullptr)
{
return false;
}
bool lson = dfs(root->left, p, q);
bool rson = dfs(root->right, p, q);
if((lson && rson) || (root->val == p->val || root->val == q->val) && (lson || rson))
{
ans = root;
}
return lson || rson || (root->val == p->val || root->val == q->val);
}
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
dfs(root, p, q);
return ans;
}
};