给定一个二叉树, 找到该树中两个指定节点的最近公共祖先。
百度百科中最近公共祖先的定义为:“对于有根树 T 的两个结点 p、q,最近公共祖先表示为一个结点 x,满足 x 是 p、q 的祖先且 x 的深度尽可能大(一个节点也可以是它自己的祖先)。”
例如,给定如下二叉树: root = [3,5,1,6,2,0,8,null,null,7,4]
示例 1:
输入: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1
输出: 3
解释: 节点 5 和节点 1 的最近公共祖先是节点 3。
思路挺简单的,调用两次dfs(前序遍历tree)记录root到p的路径,root到q的路径,返回他们路径上最后一个相同的点就是他们的LCA
/**
* 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 {
private:
bool fin;
vector<TreeNode *> ans,tmp;
void dfs(TreeNode *cur,TreeNode *target){
//if(!cur) return ;
if(fin) return ;
tmp.push_back(cur);
if(cur==target){
ans=tmp;fin=true; return ;
}
if(cur->left) dfs(cur->left,target);
if(cur->right) dfs(cur->right,target);
tmp.pop_back();
}
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if(root==NULL) return NULL;
dfs(root,p);fin=false;vector<TreeNode *>res1;res1=ans;tmp.clear();
dfs(root,q);fin=false;vector<TreeNode *>res2;res2=ans;
int len=min(res1.size(),res2.size());
int i=0;
for( ;i<len;i++){
if( res1[i]->val != res2[i]->val ) break;
}
return res1[i-1];
}
};
43.45%