#include <iostream> #define MAX 1024 using namespace std; struct node { char ch; node *lefchild,*rightchild; }; //建立二叉树 void createBitree(node* &bitree) { char ch; cin.get(ch); bitree = new node; if(ch == ' ') { bitree = NULL; } else { bitree->ch = ch; createBitree(bitree->lefchild); createBitree(bitree->rightchild); } } //先序遍历二叉树 void preOrder(node *BiTree) { if(BiTree != NULL) { cout << BiTree->ch <<" "; preOrder(BiTree->lefchild); preOrder(BiTree->rightchild); } } //中序遍历二叉树 void Inorder(node *BiTree) { if(BiTree != NULL) { Inorder(BiTree->lefchild); cout << BiTree->ch <<" "; Inorder(BiTree->rightchild); } } //后续遍历二叉树 void PostOrder(node *BiTree) { if(BiTree != NULL) { PostOrder(BiTree->lefchild); PostOrder(BiTree->rightchild); cout << BiTree->ch <<" "; } } //叶子的个数 void countLeaf(node *BiTree,int &n) { if(BiTree) { if(BiTree->lefchild == NULL && BiTree->rightchild ==NULL) { n++; } countLeaf(BiTree->lefchild,n); countLeaf(BiTree->rightchild,n); } } int max(int a, int b) { return (a > b) ? a:b; } //树的高度 int heightTree(node *BiTree) { if(BiTree == NULL) { return 0; } else { return max(1+heightTree(BiTree->rightchild) ,1+heightTree(BiTree->lefchild)); } } //输出根节点到某点的路径 void printPath(node *Bitree,char ch) { node *q = Bitree; node *s[MAX]; int top = 0; int tag[MAX]; if(q->ch == ch) { cout << q->ch<<" "; return; } while(q != NULL || top >0) { while(q != NULL) { if(q->ch == ch) { for(int i=1; i <= top; ++i) { cout << s[i]->ch <<"->"; } cout << q->ch; return; } else { s[++top] =q; tag[top] = 0; q = q->lefchild; } } while(top > 0 && tag[top] == 1) { top --; } if(top > 0) { q = s[top]; q = q->rightchild; tag[top] = 1; } } } //交换二叉树所有节点的左右子树 void exchange(node *Bitree) { int top = 0; node *s[MAX], *p = NULL; if(Bitree) { s[++top] = Bitree; while(top > 0) { Bitree = s[top--]; if(Bitree->lefchild || Bitree->rightchild) { p = Bitree->lefchild; Bitree->lefchild = Bitree->rightchild; Bitree->rightchild = p; } if(Bitree->lefchild) { s[++top] = Bitree->lefchild; } if(Bitree->rightchild) { s[++top] = Bitree->rightchild; } } } } int main() { node *bitree = NULL; char ch; //建立二叉树 cout <<"创建二叉树:"<<endl; createBitree(bitree); cout <<endl; //先序遍历二叉树 cout <<"先序遍历二叉树:" <<endl; preOrder(bitree); cout <<endl; //中序遍历二叉树 cout <<endl<< "中序遍历二叉树:"<<endl; Inorder(bitree); cout <<endl; //后序遍历二叉树 cout <<endl<< "后序遍历二叉树:"<<endl; PostOrder(bitree); cout <<endl; int n = 0; countLeaf(bitree,n); cout <<endl<< "共有 "<<n<<" 个叶子节点"<<endl; int height = 0; height = heightTree(bitree); cout <<endl<<"二叉树的高度是: "<< height << endl; cout << "请输入你要查找的字符:"<<endl; cin >> ch; cout <<"根到此节点的路径是:"<<endl; printPath(bitree,ch); cout <<endl; //交换二叉树所有节点的左右子节点 exchange(bitree); cout << "交换二叉树所有节点的左右子节点后:"<<endl; preOrder(bitree); cout <<endl; return 0; }