4.7 Design an algorithm and write code to find the first common ancestor of two nodes in a binary tree. Avoid storing additional nodes in a data structure. NOTE: This is not necessarily a binary search tree.
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
TreeNode* LCA(TreeNode *root, TreeNode *a, TreeNode *b) {
if (root == NULL) {
return NULL;
}
if (root == a || root == b) {
return root;
}
TreeNode *left = LCA(root->left, a, b);
TreeNode *right = LCA(root->right, a, b);
if (left && right) {
return root;
} else {
return left ? left : right;
}
}
本文介绍了一种寻找二叉树中两个节点的最低公共祖先(LCA)的算法,并提供了一个具体的实现代码示例。该算法避免了使用额外的数据结构来存储节点,通过递归的方式实现了高效查找。
511

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



