#include <stdio.h>
#include <stdlib.h>
// 二叉树节点结构
struct Node {
int data;
struct Node* left;
struct Node* right;
};
// 创建新节点
struct Node* createNode(int data) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
if (newNode == NULL) {
printf("内存分配失败\n");
exit(1);
}
newNode->data = data;
newNode->left = NULL;
newNode->right = NULL;
return newNode;
}
// 在二叉树中查找指定节点的双亲节点
struct Node* findParent(struct Node* root, int x) {
if (root == NULL) {
return NULL;
}
// 如果根节点就是目标节点,返回 NULL,因为根节点没有双亲节点
if (root->data == x) {
return NULL;
}
// 如果目标节点是根节点的左子节点或右子节点,返回根节点
if ((root->left != NULL && root->left->data == x) || (root->right != NULL && root->right->data == x)) {
return root;
}
// 递归在左子树中查找
struct Node* leftResult = findParent(root->left, x);
if (leftResult != NULL) {
return leftResult;
}
// 递归在右子树中查找
struct Node* rightResult = findParent(root->right, x);
if (rightResult != NULL) {
return rightResult;
}
// 如果左右子树都没有找到,返回 NULL
return NULL;
}
int main() {
// 创建二叉树
struct Node* root = createNode(1);
root->left = createNode(2);
root->right = createNode(3);
root->left->left = createNode(4);
root->left->right = createNode(5);
root->right->left = createNode(6);
root->right->right = createNode(7);
int targetNode = 5;
struct Node* parent = findParent(root, targetNode);
if (parent != NULL) {
printf("节点 %d 的双亲节点是 %d\n", targetNode, parent->data);
} else {
printf("未找到节点 %d 的双亲节点\n", targetNode);
}
// 释放内存
free(root->left->left);
free(root->left->right);
free(root->right->left);
free(root->right->right);
free(root->left);
free(root->right);
free(root);
return 0;
}