#include "stdafx.h" #include <iostream> #include <cassert> #include <stack> using namespace std; typedef struct TreeNode { char element; TreeNode* left; TreeNode* right; TreeNode(char ele, TreeNode* lchild = NULL, TreeNode* rchild = NULL) { element = ele; left = lchild; right = rchild; } }TreeNode; /* 函数功能:递归创建二叉树 */ void CreateTree1(TreeNode* &root) { char element; cin>>element; if( 'q' == element) //终止输入 return; else { root = new TreeNode(element); CreateTree1(root->left); CreateTree1(root->right); } } /* 函数功能:非递归创建二叉树 */ void CreateTree2(TreeNode* &root) { TreeNode *g = new TreeNode('G'); TreeNode *e = new TreeNode('E'); TreeNode *h = new TreeNode('H'); TreeNode *d = new TreeNode('D', NULL, g); TreeNode *b = new TreeNode('B', d, e); TreeNode *f = new TreeNode('F', NULL, h); TreeNode *c = new TreeNode('C', f, NULL); root = new TreeNode('A', b, c); } /* 函数功能:中序输出树(递归) */ void MiddleOrderPrint(TreeNode* root) { TreeNode *temp = root; if(temp == NULL) return; else { if(temp != NULL) { MiddleOrderPrint(temp->left); cout<<temp->element<<" "; MiddleOrderPrint(temp->right); } } } /* 函数功能:非递归中序输出二叉树(借助栈) */ void MiddleOrderPrint2(TreeNode *root) { stack<TreeNode*> s; TreeNode *temp = root; if (temp == NULL) return; do { while (temp != NULL) //插入左边的元素 { s.push(temp); temp = temp->left; } if (!s.empty()) { cout<<s.top()->element<<" "; temp = s.top()->right; s.pop(); } } while ((temp != NULL) || !(s.empty())); cout<<endl; } /* 函数功能:递归前序输出 */ void PreOrderPrint1(TreeNode *root) { if (root == NULL) return; else { cout<<root->element<<" "; PreOrderPrint1(root->left); PreOrderPrint1(root->right); } } /* 函数功能:非递归前序输出 */ void PreOrderPrint2(TreeNode *root) { stack<TreeNode*> s; TreeNode* temp = root; do { while (temp != NULL) //找最左边的 { cout<<temp->element<<" "; s.push(temp); temp = temp->left; } if (!s.empty()) { temp = s.top()->right; //将右字树插入 s.pop(); } } while ((temp != NULL) || !s.empty()); } /* 函数功能:递归后序输出 */ void PostOrderPrint1(TreeNode* root) { if(root == NULL) return; else { PostOrderPrint1(root->left); PostOrderPrint1(root->right); cout<<root->element<<" "; } } /* 函数功能:非递归后序输出 */ void PostOrderPrint2(TreeNode* root) { stack<TreeNode*> s; stack<TreeNode*> result; TreeNode* temp = root; do { while (temp != NULL) { s.push(temp); result.push(temp); temp = temp->right; } if (!s.empty()) { temp = s.top()->left; s.pop(); } } while ((temp != NULL) || !(s.empty())); while (!result.empty()) { cout<<result.top()->element<<" "; result.pop(); } } int main() { TreeNode *root = NULL; CreateTree2(root); cout<<"中序输出:"<<endl; MiddleOrderPrint(root); cout<<endl; MiddleOrderPrint2(root); cout<<"先序输出:"<<endl; PreOrderPrint1(root); cout<<endl; PreOrderPrint2(root); cout<<endl; cout<<"后序输出:"<<endl; PostOrderPrint1(root); cout<<endl; PostOrderPrint2(root); cout<<endl; return 0; }