二叉树三种遍历,递归和非递归实现

二叉树三种遍历

递归实现

/先序遍历
void pre_order(Tree_Node* t) {
	if (t == nullptr) {
		return;

	}
	cout << t->data << endl;
	pre_order(t->left_son);
	pre_order(t->right_son);
}

//中序遍历
void mid_order(Tree_Node* t) {
	if (t == nullptr) {
		return;

	}
	mid_order(t->left_son);
	cout << t->data << endl;
	mid_order(t->right_son);
}
//后序遍历
void post_order(Tree_Node* t) {
	if (t == nullptr) {
		return;
	}
	post_order(t->left_son);
	post_order(t->right_son);
	cout << t->data << endl;
}

非递归实现方法

//前序遍历非递归版本
void pre_order_stack(Tree_Node* root) {
	if (root != nullptr) {
		stack<Tree_Node>* stac = new stack<Tree_Node>;
		Tree_Node temp(0);
		stac->push(*root);
		while (!stac->empty()) {
			temp = stac->top();
			stac->pop();

			cout << temp.data << endl;
			if (temp.left_son != nullptr) {
				stac->push(*(temp.right_son));
			}

			if (temp.right_son != nullptr) {
				stac->push(*(temp.left_son));
			}
		}

		delete stac;
	}
}

//中序遍历的非递归版本
void mid_order_stack(Tree_Node* t) {
	//cout << "mid order print" << endl;
	if (t != nullptr) {
		stack<Tree_Node>* sta = new stack<Tree_Node>;
		Tree_Node temp(0);
		while (!sta->empty() || t != nullptr) {
			if (t != nullptr) {
				sta->push(*t);
				t = t->left_son;
			}
			else {
				t = &(sta->top());
				sta->pop();
				cout << t->data << endl;
				t = t->right_son;
			}
		}

		delete sta;
	}
}

//后序遍历非递归版本
void post_order_stack(Tree_Node* root) {
	cout << "后序遍历: " << endl;
	if (root != nullptr) {
		stack<Tree_Node> *s1 = new stack<Tree_Node>;
		stack<Tree_Node> *s2 = new stack<Tree_Node>;
		s1->push(*root);
		Tree_Node temp(0);


		while (!s1->empty()) {
			temp = (s1->top());
			s1->pop();
			s2->push(temp);
			if (temp.left_son != nullptr) {
				s1->push(*(temp.left_son));
			}

			if (temp.right_son != nullptr) {
				s1->push(*(temp.right_son));
			}

		}

		while (!s2->empty()) {
			cout << s2->top().data << endl;
			s2->pop();
		}


	}
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值