C语言用二叉树设计算法判断结点E是否为结点E1和E2的共同祖先。
时间: 2024-06-13 19:08:17 浏览: 188
以下是C语言用二叉树设计算法判断结点E是否为结点E1和E2的共同祖的步骤:
1. 定义二叉树结构体,包含左右子树指针和节点值等信息。
2. 定义一个函数,输入参数为二叉树的根节点指针、两个节点E1和E2的指针,输出参数为节点E1和E2的共同祖先节点指针。
3. 在函数中,首先判断根节点是否为空或者等于E1或E2,如果是则返回根节点。
4. 递归遍历左右子树,分别查找E1和E2的位置。
5. 如果E1和E2分别在左右子树中,则返回根节点。
6. 如果E1和E2都在左子树中,则递归遍历左子树。
7. 如果E1和E2都在右子树中,则递归遍历右子树。
以下是C语言代码实现:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
} TreeNode;
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if (root == NULL || root == p || root == q) {
return root;
}
TreeNode* left = lowestCommonAncestor(root->left, p, q);
TreeNode* right = lowestCommonAncestor(root->right, p, q);
if (left != NULL && right != NULL) {
return root;
} else if (left != NULL) {
return left;
} else {
return right;
}
}
int main() {
// 创建二叉树
TreeNode* root = (TreeNode*)malloc(sizeof(TreeNode));
root->val = 1;
root->left = (TreeNode*)malloc(sizeof(TreeNode));
root->left->val = 2;
root->left->left = (TreeNode*)malloc(sizeof(TreeNode));
root->left->left->val = 4;
root->left->left->left = NULL;
root->left->left->right = NULL;
root->left->right = (TreeNode*)malloc(sizeof(TreeNode));
root->left->right->val = 5;
root->left->right->left = NULL;
root->left->right->right = NULL;
root->right = (TreeNode*)malloc(sizeof(TreeNode));
root->right->val = 3;
root->right->left = (TreeNode*)malloc(sizeof(TreeNode));
root->right->left->val = 6;
root->right->left->left = NULL;
root->right->left->right = NULL;
root->right->right = (TreeNode*)malloc(sizeof(TreeNode));
root->right->right->val = 7;
root->right->right->left = NULL;
root->right->right->right = NULL;
// 查找共同祖先
TreeNode* p = root->left->left;
TreeNode* q = root->left->right;
TreeNode* ancestor = lowestCommonAncestor(root, p, q);
printf("The lowest common ancestor of %d and %d is %d.\n", p->val, q->val, ancestor->val);
return 0;
}
```
阅读全文