樹的 先根遍歷 後根遍歷
二叉樹的先序/中序/後序/層次遍歷 遞歸+棧 實現
#include <bits/stdc++.h>
using namespace std;
typedef char ElementType;
typedef struct BinaryTreeNode {
ElementType data;
BinaryTreeNode *l, *r;
} BinaryTreeNode, *BinaryTree;
BinaryTree CreateBinaryTree() {
char ch;
cin >> ch;
if (ch == '#')
return NULL;
BinaryTreeNode* nd = new BinaryTreeNode;
nd->data = ch;
nd->l = CreateBinaryTree();
nd->r = CreateBinaryTree();
return nd;
}
void TraverseByPre_recursion(BinaryTree bt) {
if (bt == NULL)
return;
cout << bt->data;
TraverseByPre_recursion(bt->l);
TraverseByPre_recursion(bt->r);
}
void TraverseByIn_recursion(BinaryTree bt) {
if (bt == NULL)
return;
TraverseByIn_recursion(bt->l);
cout << bt->data;
TraverseByIn_recursion(bt->r);
}
void TraverseByPost_recursion(BinaryTree bt) {
if (bt == NULL)
return;
TraverseByPost_recursion(bt->l);
TraverseByPost_recursion(bt->r);
cout << bt->data;
}
void TraverseByPre_stack(BinaryTree bt) {
BinaryTreeNode* nd = bt;
stack<BinaryTreeNode*> S;
while (!S.empty())
S.pop();
while (nd || !S.empty()) {
while (nd) {
cout << nd->data;
S.push(nd);
nd = nd->l;
}
if (!S.empty()) {
nd = S.top();
S.pop();
nd = nd->r;
}
}
}
void TraverseByIn_stack(BinaryTree bt) {
BinaryTreeNode* nd = bt;
stack<BinaryTreeNode*> S;
while (!S.empty())
S.pop();
while (nd || !S.empty()) {
while (nd) {
S.push(nd);
nd = nd->l;
}
if (!S.empty()) {
nd = S.top();
S.pop();
cout << nd->data;
nd = nd->r;
}
}
}
void TraverseByPost_stack(BinaryTree bt) {
BinaryTreeNode* nd = bt;
stack<BinaryTreeNode*> S1, S2;
while (!S1.empty())
S1.pop();
while (!S2.empty())
S2.pop();
while (nd || !S1.empty()) {
while (nd) {
S1.push(nd);
S2.push(nd);
nd = nd->r;
}
if (!S1.empty()) {
nd = S1.top();
S1.pop();
nd = nd->l;
}
}
while (!S2.empty()) {
nd = S2.top();
S2.pop();
cout << nd->data;
}
}
int main() {
BinaryTree bt = CreateBinaryTree();
cout << endl;
cout << "Recursion Traverse by Pre : ";
TraverseByPre_recursion(bt);
cout << endl;
cout << "Recursion Traverse by In : ";
TraverseByIn_recursion(bt);
cout << endl;
cout << "Recursion Traverse by Post : ";
TraverseByPost_recursion(bt);
cout << endl;
cout << endl;
cout << "Stack Traverse by Pre : ";
TraverseByPre_stack(bt);
cout << endl;
cout << "Stack Traverse by In : ";
TraverseByIn_stack(bt);
cout << endl;
cout << "Stack Traverse by Post : ";
TraverseByPost_stack(bt);
cout << endl;
return 0;
}
線索二叉樹
哈夫曼樹實現
哈夫曼編碼實現