【Openjudge】文本二叉树

重建和遍历

重建的时候,我把*看作了叶节点,但是不让其作为父节点。其他节点则可以是父节点,也可以是叶节点。

#include
#include
#include

using namespace std;

struct _node{
	char data;
	int hierachy;
	_node* left;
	_node* right;
	_node(){
		data = 0;
		hierachy = 0;
		left = NULL;
		right = NULL;
	}
};

void dlt(_node* root){
	stack<_node*> s_tree;
	s_tree.push(NULL);
	while (root){
		if (root->right){
			s_tree.push(root->right);
		}
		if (root->left){
			if (root->left->data == '*'){
				root->left = NULL;
				root = s_tree.top();	s_tree.pop();
			}
			else
				root = root->left;
		}
		else{
			root = s_tree.top();	s_tree.pop();
		}
	}
}

void preOrder(_node* root){
	stack<_node*> s_tree;
	s_tree.push(NULL);
	_node* tracker = root;
	while (tracker){
		cout << tracker->data;
		if (tracker->right){
			s_tree.push(tracker->right);
		}
		if (tracker->left){
			tracker = tracker->left;
		}
		else{
			tracker = s_tree.top();
			s_tree.pop();
		}
	}
	cout << endl;
}

void inOrder(_node* root){
	stack<_node*> s_tree;
	_node* tracker = root;
	while(!s_tree.empty() || tracker){
		if (tracker){
			s_tree.push(tracker);
			tracker = tracker->left;
		}
		else{
			tracker = s_tree.top();
			s_tree.pop();
			cout << tracker->data;
			tracker = tracker->right;
		}
	}
	cout << endl;
}

void postOrder(_node* root){
	struct _pNode{
		_node* tracker;
		int lr;
		_pNode(){
			tracker = NULL;
			lr = 0;
		}
	};
	stack<_pNode> s_pNode;
	_pNode pNode;
	s_pNode.push(pNode);
	pNode.tracker = root;
	while(!s_pNode.empty() || pNode.tracker){
		if (pNode.tracker){
			if(pNode.lr == 0){
				pNode.lr = 1;
				s_pNode.push(pNode);
				pNode.tracker = pNode.tracker->left;
				pNode.lr = 0;
			}
			else if (pNode.lr == 1){
				pNode.lr = 2;
				s_pNode.push(pNode);
				pNode.tracker = pNode.tracker->right;
				pNode.lr = 0;
			}
			else{
				cout << pNode.tracker->data;
				pNode = s_pNode.top();	s_pNode.pop();
			}
		}
		else{
			pNode = s_pNode.top();	s_pNode.pop();
		}
	}
	cout << endl;
}

int main(){
	stack<_node*> s_tree;
	int count_hierachy;
	string ts;
	int testcase;
	cin >> testcase;
	while (testcase --){
		_node* root = new _node;
		cin >> root->data;
		s_tree.push(root);
		while (cin >> ts){
			count_hierachy = 0;
			int i = 0;
			while (ts[i] == '-'){
				count_hierachy ++;
				i ++;
			}
			if (ts[i] == '0'){
				while (!s_tree.empty()){
					s_tree.pop();
				}
				break;
			}
			while (s_tree.top()->hierachy >= count_hierachy){
				s_tree.pop();
			}
			_node* parent = s_tree.top();
			if (parent->left == NULL){
				parent->left = new _node;
				parent->left->data = ts[i];
				parent->left->hierachy = count_hierachy;
				if (ts[i] != '*')
					s_tree.push(parent->left);
			}
			else if (parent->right == NULL){
				parent->right = new _node;
				parent->right->data = ts[i];
				parent->right->hierachy = count_hierachy;
				s_tree.pop();
				s_tree.push(parent->right);
			}
		}
		dlt(root);
		preOrder(root);
		postOrder(root);
		inOrder(root);
		cout << endl;
	}
	return 0;
}

你可能感兴趣的:(Openjudge)