先序、中序、后序遍历

先序遍历:本身节点,左节点,右节点

思想:想实现中、左、右就需要先压入右,再压入左。

使用栈首先把头节点压入,把头节点弹出,访问;有右节点就把右节点压入,有左节点就把左节点压入;弹出就实现了中, 左, 右

代码实现:

void preOrder(Node* head) {
	if (head == NULL) {
		return;
	}
	stack<Node*> st;
	st.push(head);
	Node* cur;

	while (!st.empty()) {
		cur = st.top();
		st.pop();
		cout << cur->value << endl;

		if (cur->right != NULL) {
			st.push(cur->right);
		}
		if (cur->left != NULL) {
			st.push(cur->left);
		}	
	}

}

 中序遍历:左中右

使用栈,当前节点不为空,压入栈且往左走;节点为空,弹出访问,且往右走。

思想:把左中看成整体,左中使用栈遍历之后,然后往右走

void inOrder(Node* head) {
	if (head == NULL) {
		return;
	}

	stack<Node*> st;
	Node* cur = head;
	while (!st.empty() || cur != NULL) {
		if (cur != NULL) {
			st.push(cur);
			cur = cur->left;
		}
		else {
			cur = st.top();
			st.pop();
			cout << cur->value << endl;
			cur = cur->right;
		}
	}
}

后序遍历:左,右,中

左, 右, 中 不好实现转变成 中, 右,左 的逆序,使用两个栈,一个栈用于实现中,右,左的输出,一个栈由于其逆序

void posOrder(Node* head) {
	if (head == NULL) {
		return;
	}
	stack<Node*> s1;//用于实现中,右,左
	stack<Node*> s2;//用于实现逆序
	Node* cur = head;
	s1.push(cur);
	
	while (!s1.empty()) {
		cur = s1.top();
		s1.pop();
		s2.push(cur);
		if (cur->left != NULL) {
			s1.push(cur -> left);
		}
		if (cur->right != NULL) {
			s1.push(cur->right);
		}
	}
	while (!s2.empty()) {
		cout << s2.top()->value << endl;
		s2.pop();
	}
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值