https://leetcode-cn.com/problems/lowest-common-ancestor-of-a-binary-tree/
思路参考 剑指offer52题
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
vector path_p;
getPath(root, p, path_p);
vector path_q;
getPath(root, q, path_q);
auto it_p = path_p.begin();
auto it_q = path_q.begin();
TreeNode *res = NULL;
while(it_p != path_p.end() && it_q != path_q.end())
{
if (*it_p != *it_q)
break;
res = *it_q;
++it_p;
++it_q;
}
return res;
}
bool getPath(TreeNode* root, TreeNode* t, vector &path)
{
if (root == NULL)
return false;
path.push_back(root);
if (root==t)
{
return true;
}
bool found = getPath(root->left, t, path) || getPath(root->right, t, path);
if (!found)
{
path.pop_back();
}
return found;
}
};
leetcode官方解答更好
class Solution {
public:
TreeNode* ans;
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
ans = NULL;
dfs(root,p,q);
return ans;
}
int dfs(TreeNode* root, TreeNode* p, TreeNode* q)
{
if (root == NULL)
return 0;
int left = dfs(root->left, p, q);
int right = dfs(root->right, p, q);
int mid = (root == p || root == q);
int sum = left+right+mid;
if (sum>=2)
{
ans = root;
}
return !!sum;
}
};