使用双栈(参数栈、状态栈)实现树的前、中、后序遍历

树结构如下:

使用双栈(参数栈、状态栈)实现树的前、中、后序遍历_第1张图片

#include 
#include 
#include 

using namespace std; 

struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode() : val(0), left(NULL), right(NULL) {}
    TreeNode(int x) : val(x), left(NULL), right(NULL) {}
    TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};

/* 
0->访问左子树 
1->访问右子树 
2->访问根节点
3->弹出本层参数 
*/

// 先序遍历:根->左->右 
vector preorder(TreeNode *root) {
	vector ret;
	if (root == NULL) return ret;
	 
	stack s1;
	stack s2;
	// 根节点压入栈中
	s1.push(root);
	s2.push(2);
	while (!s1.empty()) {
		int status = s2.top(); s2.pop();
		switch (status) {
		case 0:  // 左子树 
			s2.push(1);  // 下一状态:右子树 
			if (s1.top()->left != NULL) {
				s1.push(s1.top()->left);
				s2.push(2);
			}
			break;
		case 1: // 右子树 
			s2.push(3);
			if (s1.top()->right != NULL) {
				s1.push(s1.top()->right);
				s2.push(2);
			}
			break;
		case 2:  // 根 
			s2.push(0);  // 下一状态:左子树 
			ret.push_back(s1.top()->val);
			break;
		case 3:
			s1.pop();
			break;
		}
	}
	return ret; 
}

// 左->根->右 
vector inorder(TreeNode *root) {
	vector ret;
	stack s1;
	stack s2;
	s1.push(root);
	s2.push(0); 
	while (!s1.empty()) {
		int status = s2.top(); s2.pop();
		switch (status) {
		case 0:
			s2.push(2);
			if (s1.top()->left != NULL) {
				s1.push(s1.top()->left);
				s2.push(0); 
			}
			break;
		case 1:
			s2.push(3); 
			if (s1.top()->right != NULL) {
				s1.push(s1.top()->right);
				s2.push(0);
			}
			break;
		case 2:
			s2.push(1);
			ret.push_back(s1.top()->val);
			break;
		case 3:  // 为了清除本层的参数,引入了一个额外的状态,这个状态只负责从s1栈顶弹出本层参数 
			s1.pop();
			break;
		}
	}
	return ret;
}

// 后序遍历:左->右->根 
vector postorder(TreeNode *root) {
	vector ret;
	stack s1;  // 程序使用到的局部变量
	stack s2;  // 程序执行到的位置
	s1.push(root);
	s2.push(0);
	while (!s1.empty()) {
		int status = s2.top(); s2.pop();
		switch (status) {
			case 0:  // 左子树
				s2.push(1);
				if (s1.top()->left != NULL) {
					s1.push(s1.top()->left);
					s2.push(0);  // 将左子树压入栈中,并且设置下一状态为“打印左子树” 
				}
			break;
			case 1:  // 打印右子树
				s2.push(2);
				if (s1.top()->right != NULL) {
					s1.push(s1.top()->right);
					s2.push(0);
				}
			break;
			case 2:  // 打印根节点
				ret.push_back(s1.top()->val);
				s1.pop();
			break; 
		}
	}
	return ret;
} 

int main() {
	TreeNode *node3 = new TreeNode(3, NULL, NULL);
	TreeNode *node2 = new TreeNode(2, node3, NULL);
	TreeNode *node1 = new TreeNode(1, NULL, node2);
	vector in = inorder(node1);
	vector pre = preorder(node1);
	cout << "先序遍历:"; 
	for (auto x : pre) {
		cout << x << " ";
	}
	cout << endl; 
	cout << "中序遍历:"; 
	for (auto x : in) {
		cout << x << " ";
	}
	cout << endl; 
	vector post = postorder(node1);
	cout << "后序遍历:"; 
	for (auto x : post) {
		cout << x << " ";
	}
	return 0; 
}

 程序执行之后,输出结果如下:

使用双栈(参数栈、状态栈)实现树的前、中、后序遍历_第2张图片

你可能感兴趣的:(笔记,算法,c++)