#include<stdio.h>
#include<stdlib.h>
struct TreeNode{
int data;
struct TreeNode *left;
struct TreeNode *right;
};
struct TreeNode *createNode(int num){
struct TreeNode *T;
T=(struct TreeNode *)malloc(sizeof(struct TreeNode));
T->left=NULL;
T->right=NULL;
T->data=num;
return T;
}
struct TreeNode *createTree(struct TreeNode *T,int num){
if(T==NULL){
return createNode(num);
}
if(T->data>num){
T->left=createTree(T->left,num);
}else if(T->data<num){
T->right=createTree(T->right,num);
}
return T;
}
struct TreeNode *Parent(struct TreeNode *T,struct TreeNode *p){/*根据已知节点求父节点的核心代码*/
if(T==NULL||T==p||p==NULL){/*T==p说明p是根节点,所有没有父节点*/
return NULL;
}
if(T->left==p||T->right==p){/*在递归过程中除根节点以外的所有节点总会先被这句代码检查一次,所以T==P只会在根节点处可能被成功触发*/
return T;
}
struct TreeNode *temp;
temp=Parent(T->left,p);
if(temp!=NULL){
return temp;
}else{
return Parent(T->right,p);
}
}
void preOrder(struct TreeNode *T){
if(T!=NULL){
printf("\t%d",T->data);
preOrder(T->left);
preOrder(T->right);
}
}
void inOrder(struct TreeNode *T){
if(T!=NULL){
inOrder(T->left);
printf("\t%d",T->data);
inOrder(T->right);
}
}
void postOrder(struct TreeNode *T){
if(T!=NULL){
postOrder(T->left);
postOrder(T->right);
printf("\t%d",T->data);
}
}
int main(){
struct TreeNode *T,*re,*temp;
T=NULL;
for(int i=1;i<6;i++){
T=createTree(T,i); }
printf("二叉树:\n前序遍历:");
preOrder(T);
printf("\n中序遍历:");
inOrder(T);
printf("\n后序遍历:");
postOrder(T);
temp=T->right->right->right->right;
re=Parent(T,temp);
printf("\n父节点值为:");
if(re){
printf("%d",re->data);
}else{
printf("NULL");
}
return 0;
}