C语言用设计算法判断结点E是否为结点E1和E2的共同祖先。
时间: 2024-06-13 20:08:17 浏览: 92
C语言设计算法
以下是C语言的算法,用于判断结点E是否为结点E1和E2的共同祖先:
```
// 定义二叉树结构体
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
};
// 判断结点E是否为结点E1和E2的共同祖先
struct TreeNode* lowestCommonAncestor(struct TreeNode* root, struct TreeNode* p, struct TreeNode* q) {
if (root == NULL || root == p || root == q) {
return root;
}
struct TreeNode* left = lowestCommonAncestor(root->left, p, q);
struct TreeNode* right = lowestCommonAncestor(root->right, p, q);
if (left == NULL) {
return right;
} else if (right == NULL) {
return left;
} else {
return root;
}
}
```
阅读全文