1. 程式人生 > >二叉樹的遍歷-非遞迴

二叉樹的遍歷-非遞迴

preorder前序遍歷

在這裡插入圖片描述

void Binary_tree::preorder()const {
	stack<Node*> s;
	Node* root = this->_root;
	while (true) {
		while (root != nullptr) {
			s.push(root);
			cout << s.top()->val << " ";
			root = root->lchild;
		}
		if (s.empty())
			break;
		root = s.top()->
rchild; s.pop(); } }

inordered 中序遍歷

在這裡插入圖片描述

void Binary_tree::inorder()const {
	stack<Node*> s;
	Node* root = this->_root;
	while (true) {
		while (root != nullptr) {
			s.push(root);
			root = root->lchild;
		}
		if (s.empty())
			break;
		cout << s.top()->val << " ";
		root =
s.top()->rchild; s.pop(); } }

postorder後序遍歷

在這裡插入圖片描述

void Binary_tree::postorder() const{
	stack<Node*> s1;
	stack<Node*> s2;
	s1.push(_root);
	while (!s1.empty()) {
		Node* temp = s1.top();
		s1.pop();
		s2.push(temp);
		if (temp->lchild != nullptr) {
			s1.push(temp->lchild)
; } if (temp->rchild != nullptr) { s1.push(temp->rchild); } } while (!s2.empty()) { cout << s2.top()->val << " "; s2.pop(); } }