C++代码实现二叉树 非递归遍历

#include <iostream>
#include <cstring>
#include <vector>
#include<stack>
#include <algorithm>
using namespace std;

typedef struct node {
	node* Lchild;
	node* Rchild;
	char val;
}node;

node * createNewNode(char a) {
	node* mynode = new node;
	mynode->val = a;
	mynode->Lchild = NULL;
	mynode->Rchild = NULL;
	return mynode;
}
void insertNode(node * curNode,node* Lc, node* Rc) {
	curNode->Lchild = Lc;
	curNode->Rchild = Rc;
}
void printTree(node* root) {
	vector<char> result;
	stack<node*> st;
	if (root != nullptr) { st.push(root); }
	while (st.empty() == false) {
		node* topnode = st.top();
		if (topnode != NULL) {
			st.pop();
			if (topnode->Rchild != NULL) { st.push(topnode->Rchild); }
			if (topnode->Lchild != NULL) { st.push(topnode->Lchild); }
			st.push(topnode);
			st.push(NULL);
		}
		else {
			st.pop();
			topnode = st.top();
			st.pop();
			result.push_back(topnode->val);
		}
	}
	for (vector<char>::iterator it = result.begin(); it != result.end(); it++) {
		cout <<* it << " " << endl;
	}


}
int main() {
	node* A = createNewNode('A');
	node* B = createNewNode('B');
	node* C = createNewNode('C');
	node* D = createNewNode('D');
	node* E = createNewNode('E');
	node* F = createNewNode('F');
	insertNode(A, B, C);
	insertNode(B, D, E);
	insertNode(C, F, NULL);
	printTree(A);
	system("pause");
	return 0;
}

  

posted @ 2022-05-19 23:40  今天也是开心的一天呀  阅读(13)  评论(0)    收藏  举报