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;
}

本文介绍了一种寻找二叉树中两个指定节点的最低公共祖先(LCA)的算法。该算法包括两种情况:没有父节点指针的标准递归方法和包含父节点指针的情况。此外还探讨了一个变化问题,即找到包含所有最深节点的最小子树及其最低公共祖先。
253

被折叠的 条评论
为什么被折叠?



