观前提示:代码没有注释,里面有很多是参考别人的代码,算是备忘录。
先是我二叉树的实现方式:
class node
{
public:
int info;
node *lLink, *rLink;
node(int _info) : info(_info), lLink(NULL), rLink(NULL) {}
};
然后是周游算法:
// 递归实现
void preOrder(node *root)
{
if (root == NULL) return;
cout << root->info << ",";
preOrder(root->lLink);
preOrder(root->rLink);
}
void inOrder(node *root)
{
if (root == NULL) return;
inOrder(root->lLink);
cout << root->info << ",";
inOrder(root->rLink);
}
void postOrder(node *root)
{
if (root == NULL) return;
postOrder(root->lLink);
postOrder(root->rLink);
cout << root->info << ",";
}
// 非递归实现
void PreOrder(node *root)
{
stack<node *> s;
s.push(root);
while (!s.empty())
{
node *cur = s.top();
s.pop();
cout << cur->info << ",";
if (cur->rLink)
s.push(cur->rLink);
if (cur->lLink)
s.push(cur->lLink);
}
cout << endl;
}
void InOrder(node *root)
{
stack<node *> s;
node *cur = root;
while (cur || !s.empty())
{
while (cur)
{
s.push(cur);
cur = cur->lLink;
}
cur = s.top();
s.pop();
cout << cur->info << ",";
cur = cur->rLink;
}
cout << endl;
}
void PostOrder(node *root)
{
stack<node *> s;
node *cur = root, *pre = NULL;
while (cur || !s.empty())
{
while (cur)
{
s.push(cur);
cur = cur->lLink;
}
cur = s.top();
s.pop();
if (cur->rLink == NULL || cur->rLink == pre)
{
cout << cur->info << ",";
pre = cur;
cur = NULL;
}
else
{
s.push(cur);
cur = cur->rLink;
}
}
cout << endl;
}
void LevelOrder(node *root)
{
queue<node *>q;
q.push(root);
while (!q.empty())
{
node *cur = q.front();
q.pop();
cout << cur->info << ",";
if (cur->lLink)
q.push(cur->lLink);
if (cur->rLink)
q.push(cur->rLink);
}
cout << endl;
}
想要调用的话就这样子:
int main()
{
node *root = new node(0);
root->lLink = new node(1);
root->rLink = new node(2);
root->lLink->rLink = new node(3);
root->rLink->lLink = new node(4);
root->rLink->rLink = new node(5);
// 递归周游
preOrder(root);
cout << endl;
inOrder(root);
cout << endl;
postOrder(root);
cout << endl;
// 非递归周游
PreOrder(root);
InOrder(root);
PostOrder(root);
LevelOrder(root);
}