用先序遍历的想法,分为以下集中情况
1。对1个节点,先访问它,若它有左孩子,则继续访问左孩子
2。若节点无左孩子但是有右孩子,则访问右孩子
3。若节点无左右孩子,表示访问到1个也节点,这是要寻找下1个要访问的节点即它的先序后继节点,寻找它的方法是,一直遍历它的父辈节点,知道某父辈节点是父父辈节点的左孩子并且父父辈节点的右孩子存在,这个右孩子还没有被访问过,即是要寻找的节点,其他情况则一直向上父辈节点回溯
代码如下:
#include<iostream> #include<cstdlib> using namespace std; typedef char Elemtype; typedef struct node { Elemtype data; struct node* left; struct node* right; struct node* parent; }Tree; //先序建立一个树,不存在的元素都用0代替 Tree* create_tree(void) { Tree* root=NULL; char ch; cin>>ch; if(ch=='0') return NULL; else if(ch=='q') return root; else { root=(Tree*)malloc(sizeof(Tree)); root->data=ch; root->parent=NULL; root->left=create_tree(); root->right=create_tree(); if(root->left) root->left->parent=root; if(root->right) root->right->parent=root; } return root; } //习题10.4-5 void order(Tree* t) { Tree* p=t; while(p) { cout<<p->data<<" "; if(p->left!=NULL) { p=p->left; continue; } else if(p->right!=NULL) { p=p->right; continue; }else //都空 { while(true) { if(p==t) return ; if(p==p->parent->right) p=p->parent; if(p==t) return; if(p==p->parent->left && p->parent->right==NULL) p=p->parent; else if(p==p->parent->left && p->parent->right!=NULL) { p=p->parent->right; break; } } } } cout<<endl; } void preorder(Tree* t) { if(t) { cout<<t->data<<" "; preorder(t->left); preorder(t->right); } } void free_tree(Tree* t) { if(t) { free_tree(t->left); free_tree(t->right); free(t); } } int main(void) { Tree *root; root=create_tree(); preorder(root); cout<<endl; order(root); return 0; }
用先序顺序建立树,NULL节点用0表示,例如建立树ab0dc00e00fg0ik000hj000q,可以看到它们输出一样,都是先序顺序