二叉树三种遍历
递归实现
/先序遍历
void pre_order(Tree_Node* t) {
if (t == nullptr) {
return;
}
cout << t->data << endl;
pre_order(t->left_son);
pre_order(t->right_son);
}
void mid_order(Tree_Node* t) {
if (t == nullptr) {
return;
}
mid_order(t->left_son);
cout << t->data << endl;
mid_order(t->right_son);
}
void post_order(Tree_Node* t) {
if (t == nullptr) {
return;
}
post_order(t->left_son);
post_order(t->right_son);
cout << t->data << endl;
}
非递归实现方法
void pre_order_stack(Tree_Node* root) {
if (root != nullptr) {
stack<Tree_Node>* stac = new stack<Tree_Node>;
Tree_Node temp(0);
stac->push(*root);
while (!stac->empty()) {
temp = stac->top();
stac->pop();
cout << temp.data << endl;
if (temp.left_son != nullptr) {
stac->push(*(temp.right_son));
}
if (temp.right_son != nullptr) {
stac->push(*(temp.left_son));
}
}
delete stac;
}
}
void mid_order_stack(Tree_Node* t) {
if (t != nullptr) {
stack<Tree_Node>* sta = new stack<Tree_Node>;
Tree_Node temp(0);
while (!sta->empty() || t != nullptr) {
if (t != nullptr) {
sta->push(*t);
t = t->left_son;
}
else {
t = &(sta->top());
sta->pop();
cout << t->data << endl;
t = t->right_son;
}
}
delete sta;
}
}
void post_order_stack(Tree_Node* root) {
cout << "后序遍历: " << endl;
if (root != nullptr) {
stack<Tree_Node> *s1 = new stack<Tree_Node>;
stack<Tree_Node> *s2 = new stack<Tree_Node>;
s1->push(*root);
Tree_Node temp(0);
while (!s1->empty()) {
temp = (s1->top());
s1->pop();
s2->push(temp);
if (temp.left_son != nullptr) {
s1->push(*(temp.left_son));
}
if (temp.right_son != nullptr) {
s1->push(*(temp.right_son));
}
}
while (!s2->empty()) {
cout << s2->top().data << endl;
s2->pop();
}
}
}