zig tag traversal a binary tree

#include<iostream>
#include<vector>
using namespace std;

typedef struct tree_node_s {
	int value;
	struct tree_node_s* lchild;
	struct tree_node_s* rchild;
}tree_node_t;

tree_node_t* createNode(int value) {
	tree_node_t* node = (tree_node_t*)malloc(sizeof(tree_node_t));
	node->value = value;
	node->lchild = NULL;
	node->rchild = NULL;
	return node;
}

void zig_tag_traversal(tree_node_t* root) {
	int level = 1;
	int cur = 0;
	int last = 0;
	vector<tree_node_t*> vec;
	int temp_cur;
	int temp_last;
	vec.push_back(root);
	while (cur < vec.size()) {
		last = vec.size();
		temp_cur = cur;
		temp_last = last;
		if (1 == level % 2) {
			while (temp_cur < temp_last) {
				cout << vec[temp_cur]->value << " ";
				temp_cur++;
			}
		} else {
			while (temp_last >  temp_cur) {
				cout << vec[temp_last - 1]->value << " ";
				temp_last--;
			}
		}
		while(cur < last) {
			if (vec[cur]->lchild)
				vec.push_back(vec[cur]->lchild);
			if (vec[cur]->rchild)
				vec.push_back(vec[cur]->rchild);
			cur++;
		}
		level++;
	}
}

int main(int argc, char* argv[]) {
	tree_node_t* root = createNode(1);
	root->lchild = createNode(2);
	root->rchild = createNode(3);
	root->lchild->lchild = createNode(4);
	root->lchild->rchild = createNode(5);
	root->rchild->lchild = createNode(6);
	root->rchild->rchild = createNode(7);
	zig_tag_traversal(root);
	cin.get();
	return 0;
}

1,3,2,4,5,67

你可能感兴趣的:(zig tag traversal a binary tree)