手撕树~非递归三种遍历

#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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值