二叉树遍历

先序遍历: 根 ,左,右

中序遍历: 左 ,根,右

后序遍历: 左 ,右,根

 

遍历的两种核心方法:1递归,2利用栈实现

 

1递归实现

#include<malloc.h> #include <string> #include <iostream> using namespace std; #define OK 1 #define FALSE 0 typedef char status; typedef struct Node { status data; struct Node *LTree,*RTree; }BinaryTree; /*PreCreateTree先序创建BinaryTree*/ void PreCreateTree(BinaryTree* & head) { char ch; scanf("%c",&ch); if(ch=='#') { head=NULL; } else { head=(BinaryTree *)malloc(sizeof(BinaryTree)); head->data=ch; PreCreateTree(head->LTree); PreCreateTree(head->RTree); } } void InOrderTraverse(BinaryTree *head) { if (head) { InOrderTraverse(head->LTree); printf("%c",head->data); InOrderTraverse(head->RTree); } } void PreOrderTraverse(BinaryTree *head) { if (head != NULL) { printf("%c",head->data); PreOrderTraverse(head->LTree); PreOrderTraverse(head->RTree); } } void PastOrderTraverse(BinaryTree *head) { if (head != NULL) { PastOrderTraverse(head->LTree); PastOrderTraverse(head->RTree); printf("%c",head->data); } } int main() { BinaryTree *head=NULL; printf("先序建树:"); PreCreateTree(head); printf("先序遍历:"); PreOrderTraverse(head); printf("/n"); printf("中序遍历:"); InOrderTraverse(head); printf("/n"); printf("后序遍历:"); PastOrderTraverse(head); printf("/n"); return 0; }  

 


 

2堆栈实现

#include <iostream> #include <stack> using namespace std; struct TreeNode { int data; TreeNode* left; TreeNode* right; int flag; }; typedef TreeNode *TreePtr; TreePtr CreateTree() { TreePtr root = new TreeNode; cout<<"input the data :/n"; int n; cin>>n; if (n == -1) { return NULL; } else { root->data = n; root->flag = 0; root->left = CreateTree(); root->right = CreateTree(); } return root; } void PreOrderNoRecursion(TreePtr p) { cout<<"PreOrderNoRecursion/n"; stack<TreeNode> stk; TreeNode t = *p; stk.push(t); while (!stk.empty()) { t = stk.top(); stk.pop(); cout<<t.data<<" "; if (t.right != NULL) { stk.push((*t.right)); } if (t.left != NULL) { stk.push((*t.left)); } } } void InOrderNoRecursion(TreePtr p) { cout<<"InOrderNoRecursion/n"; stack<TreeNode> stk; TreeNode t = *p; stk.push(t); while (!stk.empty()) { if (stk.top().flag == 0) { stk.top().flag++; if (stk.top().left != NULL) { stk.push(*(stk.top().left)); } } else { t = stk.top(); stk.pop(); cout<<t.data<<" "; if (t.right != NULL) { stk.push(*(t.right)); } } } } void PostOrderNoRecursion(TreePtr p) { cout<<"PostOrderNoRecursion/n"; stack<TreeNode> stk; TreeNode t = *p; stk.push(t); while (!stk.empty()) { if (stk.top().flag == 0) { stk.top().flag++; if (stk.top().left != NULL) { stk.push(*(stk.top().left)); } } else if (stk.top().flag == 1) { stk.top().flag++; if (stk.top().right != NULL) { stk.push(*(stk.top().right)); } } else { cout<<stk.top().data<<" "; stk.pop(); } } } int main() { TreePtr t = CreateTree(); PreOrderNoRecursion(t); cout<<"/n"; InOrderNoRecursion(t); cout<<"/n"; PostOrderNoRecursion(t); cout<<"/n"; }  

另外的例子:给出先序和中序序列求后序序列,见另一个日志

你可能感兴趣的:(c,struct,null,input,iostream)