#include<iostream>
#include<stdlib.h>
#include<vector>
#include<string.h>
#include<stack>
#include<algorithm>
using namespace std;
struct TreeNode {
int val;
TreeNode* lchild;
TreeNode* rchild;
TreeNode(int val) {
this->val = val;
this->lchild = nullptr;
this->rchild = nullptr;
}
};
TreeNode* creatTree(vector<int>&a) {
sort(a.begin(), a.end());
int mid = a.size() / 2;
TreeNode* root = new TreeNode(a[mid]);
for (int i = 0; i < a.size(); i++) {
TreeNode* newnode = new TreeNode(a[i]);
TreeNode* p = root;
while (p) {
if (a[i] < p->val) {
if (p->lchild==nullptr) {
p->lchild = newnode;
break;
}
p = p->lchild;
}
if(a[i] > p->val){
if (p->rchild==nullptr) {
p->rchild = newnode;
break;
}
p = p->rchild;
}
else break;
}
}
return root;
}
//先根
void pre_print(TreeNode* root) {
if (!root) return;
stack<TreeNode*>stk;
stk.push(root);
while (stk.size()) {
TreeNode* tmp = stk.top();
stk.pop();
cout << tmp->val;
if (tmp->rchild) {
stk.push(tmp->rchild);
}
if (tmp->lchild) {
stk.push(tmp->lchild);
}
}
}
//中根
void mid_print(TreeNode* root) {
if (!root) return;
stack<TreeNode*>stk;
while (root||stk.size()) {
if (root) {
stk.push(root);
root = root->lchild;
}
else {
TreeNode* tmp = stk.top();
stk.pop();
cout << tmp->val;
root = tmp->rchild;
}
}
}
//后根
void last_print(TreeNode* root) {
if (!root) return;
stack<TreeNode*>stk,res;
stk.push(root);
while (stk.size()) {
TreeNode* tmp = stk.top();
stk.pop();
res.push(tmp);
if (tmp->lchild) {
stk.push(tmp->lchild);
}
if (tmp->rchild) {
stk.push(tmp->rchild);
}
}
while (res.size()) {
cout << res.top()->val;
res.pop();
}
}
int main() {
vector<int>a = {1,4,2,5,3};
TreeNode* root= creatTree(a);
pre_print(root);//31245
cout << endl;
mid_print(root);//12345
cout << endl;
last_print(root);//21543
return 0;
}
手撕树~非递归三种遍历
最新推荐文章于 2024-07-28 11:06:12 发布