Trying my hand at Leet 236
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).”
This is the first version.
My final version can be found here.
This version my thought lets brute force this to see if I can do it.
/**
* 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 {
public:
bool findPath(TreeNode* root, TreeNode* dst, std::vector<TreeNode*>& path) {
if (root == nullptr) {
return false;
}
path.push_back(root);
if (root == dst) {
return true;
}
if (findPath(root->left, dst, path)) {
return true;
}
if (findPath(root->right, dst, path)) {
return true;
}
path.pop_back();
return false;
}
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
std::vector<TreeNode*> pPath;
findPath(root, p, pPath);
//std::cout << "pSize: " << pPath.size() << "\n";
std::vector<TreeNode*> qPath;
findPath(root, q, qPath);
//std::cout << "qSize: " << qPath.size() << "\n";
TreeNode* best = root;
for (std::size_t loop = 0; true; ++loop) {
if (loop >= pPath.size() || loop >= qPath.size()) {
//std::cout << "Loop: " << loop << "\n";
break;
}
//std::cout << "L: " << loop << " p: " << pPath[loop]->val << " q: " << qPath[loop]->val << "\n";
if (pPath[loop] != qPath[loop]) {
break;
}
best = pPath[loop];
}
return best;
}
};