树的递归与非递归
#include<iostream>
#include<vector>
#include<stack>
using namespace std;
class TreeNode
{
public:
TreeNode(int data):val(data){};
~TreeNode();
int val;
TreeNode* left;
TreeNode* right;
};
TreeNode* creatTree() {
int a = 0;
cin >> a;
if (a == -1)
return NULL;
TreeNode* head = new TreeNode(a);
head->left = creatTree();
head->right = creatTree();
return head;
}
void Print_pre(TreeNode* head)
{
if(head==NULL)
return;
cout<<head->val<<"->";
Print_pre(head->left);
Print_pre(head->right);
}
void Print_pre1(TreeNode* head)
{
stack<TreeNode*> node;
node.push(head);
TreeNode* theOne;
while (!node.empty())
{
theOne=node.top();
cout << theOne->val << "->";
node.pop();
if(theOne->right!=NULL)
node.push(theOne->right);
if(theOne->left!=NULL)
node.push(theOne->left);
}
return ;
}
void Print_mid(TreeNode* head)
{
if (head == NULL)
return;
Print_mid(head->left);
cout << head->val << "->";
Print_mid(head->right);
}
void Print_mid1(TreeNode* head)
{
stack<TreeNode*> node;
while (!node.empty()||head!=NULL)
{
if(head!=NULL)
{
node.push(head);
head=head->left;
}
else
{
head=node.top();
node.pop();
cout<< head->val << "->";
head=head->right;
}
}
}
void Print_las(TreeNode* head) {
if (head == NULL)
return;
Print_las(head->left);
Print_las(head->right);
cout << head->val << "->";
}
void Print_las1(TreeNode* head) {
stack<TreeNode*> node1;
stack<TreeNode*> node2;
node1.push(head);
TreeNode* theOne;
while(!node1.empty()){
theOne = node1.top();
node2.push(theOne);
node1.pop();
if(theOne->left != NULL) node1.push(theOne->left);
if(theOne->right != NULL) node1.push(theOne->right);
}
while(!node2.empty()){
cout<<node2.top()->val<<"->";
node2.pop();
}
return;
}
int main() {
cout << "请输入要建立的二叉树:1 1 -1 -1" << endl;
TreeNode* head = creatTree();
cout<<"前序遍历:"<<endl;
Print_pre(head); cout << endl;
Print_pre1(head); cout << endl;
cout<<"中序遍历:"<<endl;
Print_mid(head); cout << endl;
Print_mid1(head); cout << endl;
cout<<"后序遍历:"<<endl;
Print_las(head); cout << endl;
Print_las1(head); cout << endl;
system("pause");
return 0;
}