Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree.
The problem will get interesting if the tree node has parent node. (....need to be continued)
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if(!root) return NULL;
if(root == p || root == q) return root;
TreeNode* tmp_1 = lowestCommonAncestor(root->left, p, q);
TreeNode* tmp_2 = lowestCommonAncestor(root->right, p, q);
if(tmp_1 && tmp_2) return root;
return tmp_1 ? tmp_1 : tmp_2;
}
Or, if given the TreeNode has a parent pointer.
class TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNoe* parent;
};
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if(!root) return NULL;
unordered_set<TreeNode*> nodes;
while(p || q) {
if(p) {
if(!nodes.insert(p).second) return p;
p = p->parent;
}
if(q) {
if(!nodes.insert(q).second) return q;
q = q->parent;
}
}
return NULL;
}
One more variation:
/*
Give a tree, find the smallest substree that contains all the tree's deepest nodes.
a
/ \
b d
/\ |
e f g
/ / \
h i j
*/
/*
depth of tree: 4
deepest nodes: [h, i, j]
least common ancestor of [h, i, j] : b
return b.
*/
int getDepth(TreeNode* root) {
if(!root) return 0;
return 1 + max(getDepth(root->left), getDepth(root->right));
}
void findCommnNode(TreeNode* root, TreeNode* a, TreeNode* b) {
}
TreeNode* leastCommonAncestor(TreeNode* root) { // pseudo-code
int depth = getDepth(root);
vector<TreeNode*> leaves = TreeLeaves(root, depth);
if(leaves.size() == 1) return root;
TreeNode* commonNode = leaves[0];
for(int i = 1; i < leaves.size(); ++i) {
findCommonNode(root, leaves[i], commonNode);
if(commonNode == root) break;
}
return commonNode;
}