1. 程式人生 > 其它 >前後端資料的互動

前後端資料的互動

#include<iostream>
#include<stack>
#include<vector>
struct TreeNode {
	int val;
	TreeNode *left;
	TreeNode *right;
	TreeNode(int x) { val = x; left = nullptr; right = nullptr; };
};
using namespace std;
//二叉樹前序非遞迴遍歷
void preOrder(TreeNode * root) {
	stack<TreeNode*> s;
	while (root !=nullptr || !s.empty())
	{
		while(root!=nullptr){
			cout << " " << root->val;
			s.push(root);
			root = root->left;
		}
		if (!s.empty())
		{
			root = s.top();
			s.pop();
			root = root->right;

		}
	}
}

//非遞迴中序遍歷
void inorder(TreeNode * root) {
	stack<TreeNode *> s;
	while (!s.empty() || root!=nullptr)
	{
		while(root !=nullptr){
			s.push(root);
			root = root->left;
		}
		if (!s.empty()) {
			root = s.top();
			cout << " " << root->val;
			s.pop();
			root= root->right;
		}
	}
}

//非遞迴後序遍歷
void postOrder(TreeNode * root) {
	stack<TreeNode *> s;
	TreeNode *cur = root;
	TreeNode *pre = nullptr;
	while (cur!=nullptr || !s.empty())
	{
		while (cur !=nullptr)
		{
			s.push(cur);
			cur = cur->left;
		}
		if(!s.empty()){
			TreeNode* cur= s.top();
			if (cur->right == nullptr || pre == cur->right) {
				cout << " " << cur->val;
				pre = cur;
				cur = nullptr;
				s.pop();
			}else{
				cur = cur->right;
				while (cur)
				{
					s.push(cur);
					cur = cur->left;
				}
			}
		}

	}
}
TreeNode* makeTree() {
	TreeNode* root = nullptr;
	root=new TreeNode(1);
	TreeNode* node2 = new TreeNode(8);
	TreeNode* node3 = new TreeNode(3);
	TreeNode* node4 = new TreeNode(4);
	TreeNode* node5 = new TreeNode(5);
	TreeNode* node6 = new TreeNode(6);
	root->left = node2; root->right = node5;
	node2->left = node3; node2->right = node4;
	node5->left = node6;
	return root;
}
int main() {
	TreeNode * root = makeTree();
	cout << endl << "二叉樹非遞迴前序遍歷" << endl;
	preOrder(root);
	cout << endl << "二叉樹非遞迴中序遍歷" << endl;
	inorder(root);
	cout << endl << "二叉樹非遞迴後序遍歷" << endl;
	postOrder(root);
	return 0;
}