#include<stdio.h> #include<malloc.h> typedef char ElemType; typedef struct BiTNode { ElemType data; struct BiTNode* lchild, * rchild; }BiTNode,*BiTree; BiTNode* p=(BiTree)malloc(sizeof(BiTNode)); //记录目标节点 BiTNode* pre = NULL; //指向当前访问节点的前驱 BiTNode* final; //记录最终结果 bool IniTree(BiTree &T) { ElemType ch; ch = getchar(); if (ch == '#') { T = NULL; } else { T = (BiTree)malloc(sizeof(BiTNode)); T->data = ch; if (T->lchild != NULL) IniTree(T->lchild); if (T->rchild != NULL) IniTree(T->rchild); } return true; } void visit(BiTree t) { printf("%c\t", t->data); } void visitPre(BiTree t) { if (t->data == p->data) final = pre; else pre = t; //pre指向当前访问的节点 } bool InOrder1(BiTree t) { if (t == NULL) { return false; } if(t!=NULL) { InOrder1(t->lchild); visit(t); InOrder1(t->rchild); return true; } } bool InOrder2(BiTree t) { if (t == NULL) { return false; } if (t != NULL) { InOrder2(t->lchild); visitPre(t); InOrder2(t->rchild); return true; } } int main() { BiTree T; p->data='D'; printf("初始化二叉树,ps:#表示空树:"); IniTree(T); printf("\n二叉树中序遍历:"); InOrder1(T); InOrder2(T); if (final != NULL) printf("\n节点%c中序前驱:%c", p->data, final->data); else printf("\n节点%c无前驱\n"); return 0; }