Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree.
According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes p and q as the lowest node in T that has both p and q as descendants (where we allow a node to be a descendant of itself).”
Given the following binary tree: root = [3,5,1,6,2,0,8,null,null,7,4]
Example 1:
Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1 Output: 3 Explanation: The LCA of nodes5
and1
is3.
/* 找出p q最邻近祖先
* 用vector<> 记录path 递归进入时计入 返回时删除
* 从头遍历两个path 输出最后一次相同的节点
*
* */
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if(!root || !p || !q) return NULL;
vector<TreeNode*> pathP, pathQ;
bool foundP=false, foundQ= false;
dfs(root, pathP, p, foundP);
dfs(root, pathQ, q, foundQ);
TreeNode *ret=root;
for(int i=0;i<min(pathP.size(), pathQ.size());i++){
if(pathP[i] == pathQ[i]) ret = pathP[i];
else break;
}
return ret;
}
void dfs(TreeNode* root, vector<TreeNode*> &path, TreeNode *tar, bool &found){
if(root == tar){
found = true;
return;
}
if(!found && root->left){
path.push_back(root->left);
dfs(root->left, path, tar, found);
if(!found) path.pop_back(); // 非常重要 不然在找到之后再递归返回时会pop出父节点
}
if(!found && root->right){
path.push_back(root->right);
dfs(root->right, path, tar, found);
if(!found) path.pop_back();
}
}
};
递归的解决方法:
/* 找出p q最邻近祖先
* 递归想法: 首先这个函数是求以root为根节点的p和q的LCA(lowest common ancester)
* root = p 或者 root=q 是一种边界条件 (递归到了这个节点) 还有一种root=NULL eg: 起始pq都在root左分支上
* 对右分支递归的结果返回NULL
*
* 递归情况:
* 1. p,q 在 左右 分支上
* 2. p,q 都在左分支上 右分支返回NULL
* 3. p,q 都在右分支上 左分支返回NULL
* */
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if(!root || root==p || root==q) return root;
auto left = lowestCommonAncestor(root->left, p, q);
auto right = lowestCommonAncestor(root->right, p, q);
if(!left) return right;
else if(!right) return left;
else return root; // left!=NULL && right!=NULL
}
};