9.19
完成了二叉树先中后递归和非递归遍历,以及层序遍历
#include<iostream>
#include<queue>
#include<stack>
using namespace std;
struct TreeNode{
char val;
TreeNode* left;
TreeNode* right;
TreeNode() : val(0), left(nullptr), right(nullptr) {}
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
TreeNode(int x, TreeNode *left, TreeNode *right) : val(x),left(left), right(right) {}
};
void preorder(TreeNode* root){
if(root==NULL) return;
cout<<root->val<<' ';
preorder(root->left);
preorder(root->right);
}
void inorder(TreeNode* root){
if(root==NULL) return;
inorder(root->left);
cout<<root->val<<' ';
inorder(root->right);
}
void postorder(TreeNode* root){
if(root==NULL) return;
postorder(root->left);
postorder(root->right);
cout<<root->val<<' ';
}
void levelorder(TreeNode* root){
queue<TreeNode*> q;
q.push(root);
while(q.size()){
TreeNode* node=q.front();
q.pop();
cout<<node->val<<' ';
if(node->left) q.push(node->left);
if(node->right) q.push(node->right);
}
}
void preorder2(TreeNode* root){
stack<TreeNode*> s;
s.push(root);
while(s.size()){
TreeNode* node=s.top();
s.pop();
cout<<node->val<<' ';
if(node->right) s.push(node->right);
if(node->left) s.push(node->left);
}
}
void inorder2(TreeNode* root){
stack<TreeNode*> s;
TreeNode* curr=root;
while(curr||s.size()){
while(curr){
s.push(curr);
curr=curr->left;
}
curr=s.top();
s.pop();
cout<<curr->val<<' ';
curr=curr->right;
}
}
void postorder2(TreeNode* root){
stack<TreeNode*> s;
TreeNode* curr=root;
TreeNode* prev=NULL;
while(curr||s.size()){
while(curr){
s.push(curr);
curr=curr->left;
}
curr=s.top();
if(curr->right==NULL||curr->right==prev){
s.pop();
cout<<curr->val<<' ';
prev=curr;
curr=NULL;
}else curr=curr->right;
}
}
int main()
{
TreeNode *root = new TreeNode('A',
new TreeNode('B',
new TreeNode('D'),
new TreeNode('E')),
new TreeNode('C'));
// preorder(root);
// cout<<endl;
// inorder(root);
// cout<<endl;
postorder(root);
cout<<endl;
// levelorder(root);
// cout<<endl;
// preorder2(root);
// cout<<endl;
// inorder2(root);
// cout<<endl;
postorder2(root);
return 0;
}