//前序遍历 根->左子树->右子树
void btree_foreach_prev2(BTree tree,void (*foreach)(T)){
if(tree == NULL)
return;
Stack s;
stack_init(&s,btree_size(tree));
stack_push(&s,tree);
while(!stack_is_empty(&s)){
BNode *node = stack_pop(&s);
foreach(node->data);
if(node->right!=NULL){
stack_push(&s,node->right);
}
if(node->left!=NULL){
stack_push(&s,node->left);
}
}
stack_destroy(&s);
}
//中序遍历 左子树=>根->右子树
void btree_foreach_mid2(BTree tree,void (*foreach)(T)){
if(tree == NULL)
return;
Stack s;
stack_init(&s,btree_size(tree));
BNode *p = tree;
while(p!=NULL||!stack_is_empty(&s)){
while(p!=NULL){
stack_push(&s,p);
p = p->left;
}
if(!stack_is_empty(&s)){
p = stack_pop(&s);
foreach(p->data);
p = p->right;
}
}
stack_destroy(&s);
}
//后序遍历 左子树->右子树->根
void btree_foreach_last2(BTree tree,void (*foreach)(T)){
if(tree == NULL)
return;
Stack s;
stack_init(&s,btree_size(tree));
Stack res;
stack_init(&res,btree_size(tree));
stack_push(&s,tree);
while(!stack_is_empty(&s)){
tree = stack_pop(&s);
stack_push(&res,tree);
if(tree->left!=NULL){
stack_push(&s,tree->left);
}
if(tree->right!=NULL){
stack_push(&s,tree->right);
}
}
while(!stack_is_empty(&res)){
tree = stack_pop(&res);
foreach(tree->data);
}
stack_destroy(&s);
stack_destroy(&res);
}
//按二叉树的层遍历
void btree_layer_foreach(BTree tree,void (*foreach)(T)){
if(tree == NULL){
return;
}
Queue que;
queue_init(&que,btree_size(tree));
queue_push(&que,tree);
while(!queue_is_empty(&que)){
BNode *node = queue_pop(&que);
foreach(node->data);
if(node->left != NULL){
queue_push(&que,node->left);
}
if(node->right != NULL){
queue_push(&que,node->right);
}
}
queue_destroy(&que);
}