完整的给出二叉树递归建立和非递归先序,递归后序代码
#include <iostream>
#include <stdlib.h>
#include <stdio.h>
#include <stack>
#include <vector>
using namespace std;
//Definition for binary tree
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution {
public:
TreeNode *creat(){
TreeNode *root;
int t;
cout<<"input the value of the node"<<endl;
cin>>t;
if(t==0)
root=NULL;
else{
root=new TreeNode(0);
root->val=t;
root->left=creat();
root->right=creat();
}
return root;
}
void postorder(TreeNode *root,vector<int> &r){
if(root!=NULL){
postorder(root->left,r);
postorder(root->right,r);
r.push_back(root->val);
}
else
return;
}
vector<int> postorderTraversal(TreeNode *root) {
vector<int> r;
postorder(root,r);
return r;
}
vector<int> preorderTraversal(TreeNode *root) {
vector<int> re;
stack<TreeNode*> s;
if(root==NULL)
return re;
s.push(root);
while(!s.empty()){
TreeNode *node;
node=s.top();
s.pop();
re.push_back(node->val);
if(node->right)
s.push(node->right);
if(node->left)
s.push(node->left);
}
return re;
}
};
int main(){
Solution trees;
TreeNode *root;
vector<int> pre,post;
//typedef vector<int>::iterator viterator;
root=trees.creat();
pre=trees.preorderTraversal(root);
post=trees.postorderTraversal(root);
cout<<"preorder"<<endl;
for(int i=0;i<pre.size();i++)
cout<<pre[i]<<" ";
cout<<endl<<"postorder"<<endl;
for(int i=0;i<post.size();i++)
cout<<post[i]<<" ";
return 0;
}