奇了怪,data无法赋值,使用scanf也不行,只能初始化时赋值
int main(){char data;bitree root=NULL;create(&root);printf("请输入寻找的结点:");data = getchar();printf("结果为:n"); path(root,data);return 0;} 题目求出二叉树根节点到r节点之间的路径
分析由于后序遍历访问到r所指节点时,此时栈中所有节点均为r所指节点的祖先,由这些祖先构成了一条从根节点到r所指节点之间的路径,故采用后序遍历方法
由于递归方式的栈区是由系统隐式控制,为了能在找到结点r时控制输出,需要将递归方式中系统隐含的栈变成用户自己控制的栈,所以应该使用非递归的后序遍历
代码 #include "stdio.h"#include "malloc.h"#define LEN sizeof(bitnode)#define max 20typedef struct node{char ch;struct node *lchild; struct node *rchild; }*bitree,bitnode;void create(bitree *root ){char ch;ch = getchar();if(ch=='.'){*root = NULL;return;}else{*root = (bitree)malloc(LEN);(*root)->ch = ch;create(&((*root)->lchild));create(&((*root)->rchild));}}void path(bitree root,char ch){bitree s[max];int top=0,i;bitree p,q;p=root;q=NULL;while(p!=NULL||top!=0){//遍历左子树if(p){s[++top]=p;p=p->lchild;}else{p = s[top];//右子树为空或者右子树已经访问if(p->rchild==NULL||p->rchild==q){if(p->ch==ch){for(i=1;i<=top;i++)printf("%c ",s[i]->ch);return;}else{//q保存已经访问过的结点q=p;top--;p=NULL;}}//遍历右子树else p=p->rchild;}}}int main(){char data='c';bitree root=NULL;create(&root);//printf("请输入寻找的结点:");//data = getchar();printf("结果为:n"); path(root,data);return 0;}