#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,int key,int height){/*求父节点的核心代码*/
if(T==NULL||(height==1&&T->data==key)){
return NULL;
}
if(T->left!=NULL&&T->left->data==key||T->right!=NULL&&T->right->data==key){
return T;
}
struct TreeNode *temp;
temp=Parent(T->left,key,height+1);
if(temp!=NULL){
return temp;
}else{
return Parent(T->right,key,height+1);
}
}
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;
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);
int key=4;
re=Parent(T,key,1);
printf("\n值为4的节点的父节点值为:");
if(re){
printf("%d",re->data);
}else{
printf("NULL");
}
return 0;
}
?
|