本文共 2158 字,大约阅读时间需要 7 分钟。
struct Tree{ int date; Tree* lchild; Tree* rchild; Tree(int x):date(x),lchild(nullptr),rchild(nullptr){}};void PreOrder(Tree* root){ if (root != nullptr) { cout << root->date << " "; PreOrder(root->lchild); PreOrder(root->rchild); }}
void PreOrder(Tree* root){ stackStack; if (root == nullptr) return; while (root != nullptr || !Stack.empty()) { while (root != nullptr) { Stack.push(root); cout << root->date << " "; root = root->lchild; } root = Stack.top(); Stack.pop(); root = root->rchild; }}
void InOrder(Tree* root){ if (root != nullptr) { InOrder(root->lchild); cout << root->date << " "; InOrder(root->rchild); }}
void InOrder(Tree* root){ stacks; while (root != nullptr || !s.empty()) { if (root != nullptr) { s.push(root); root = root->lchild; } else { root = s.top();s.pop(); cout << root->date << " "; root = root->rchild; } }}
void PostOrder(Tree* root){ if (root != nullptr) { PostOrder(root->lchild); PostOrder(root->rchild); cout << root->date << " "; }}
void PostOrder(Tree* root){ stacks; Tree* r = nullptr;//使用辅助指针,指向最近访问过的节点 while (root != nullptr || !s.empty()) { if (root != nullptr) { s.push(root); root = root->lchild; } else { root = s.top(); if (root->rchild != nullptr && root->rchild != r) root = root->rchild; else { s.pop(); cout << root->date << " "; r = root; root = nullptr; } } }}
void LevelOrder(Tree* root){ if (root == nullptr) return; queueque; que.push(root); while (!que.empty()) { root = que.front(); cout << root->date << " "; que.pop(); if (root->lchild != nullptr) que.push(root->lchild); if (root->rchild != nullptr) que.push(root->rchild); }}
void LevelOrder(Tree* root){ if (root == nullptr) return; queueque; que.push(root); while (!que.empty()) { int size = que.size(); while (size) { root = que.front(); cout << root->date << " "; que.pop(); if (root->lchild != nullptr) que.push(root->lchild); if (root->rchild != nullptr) que.push(root->rchild); --size; } }}
转载地址:http://stwab.baihongyu.com/