236.二叉树的最近公共祖先
https://leetcode-cn.com/problems/lowest-common-ancestor-of-a-binary-tree/
给定一个二叉树, 找到该树中两个指定节点的最近公共祖先。
百度百科中最近公共祖先的定义为:“对于有根树 T 的两个结点 p、q,最近公共祖先表示为一个结点 x,满足 x 是 p、q 的祖先且 x 的深度尽可能大(一个节点也可以是它自己的祖先)。”
例如,给定如下二叉树: root = [3,5,1,6,2,0,8,null,null,7,4]
这一题算是上一题的加难版,树的结构更为普遍
同样使用递归判断p,q在是否在左子树或者右子树中,又或者是在根节点
class Solution {
public:
TreeNode* ans = NULL;
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
helper(root,p,q);
return ans;
}
bool helper(TreeNode* currentNode,TreeNode* p,TreeNode* q){
if(currentNode==NULL) return false;
int left = helper(currentNode->left,p,q)?1:0;
int right = helper(currentNode->right,p,q)?1:0;
int mid = (currentNode==p)||(currentNode==q)?1:0;
if(left+right+mid>=2){
ans = currentNode;
}
return (left+mid+right>0);
}
};