Some concepts
Full binary tree: All branch nodes have left and right subtrees, and all leaves are on the bottom layer.
Complete binary tree: Leaf nodes can only appear in the lowest and second lowest levels, and the lowest leaf nodes are concentrated in the left part of the tree.
Create & initialize binary tree
typedef int datatype;
typedef struct bitnode{
datatype data;
struct bitnode * lchild, * rchild;
} BiTNode, * BiTree;
BiTree Inatiate ( ) {
BiTNode * bt;
bt= ( BiTNode* ) malloc ( sizeof ( BiTNode) ) ;
bt- > lchild= NULL ;
bt- > rchild= NULL ;
return bt;
}
BiTree Create_BiTree ( datatype x, BiTree lbt, BiTree rbt) {
BiTree p;
p= ( BiTNode* ) malloc ( sizeof ( BiTNode) ) ;
p- > data= x;
p- > lchild= lbt;
p- > rchild= rbt;
return p;
}
BiTree Insert_Bitree ( BiTree bt, datatype x, BiTree parent) {
BiTree p;
p= ( BiTNode* ) malloc ( sizeof ( BiTNode) ) ;
p- > data= x;
p- > lchild= NULL ;
p- > rchild= NULL ;
if ( parent- > lchild= NULL )
parent- > lchild= p;
else {
p- > lchild= parent- > lchild;
p- > rchild= parent- > rchild;
}
return bt;
}
BiTree Delete_Bitree ( BiTree bt, BiTree parent) {
BiTree p;
p= parent- > lchild;
parent- > lchild= NULL ;
free ( p) ;
return bt;
}
Three kinds of traversal of binary tree
Recursive version
void Visit ( BiTree bt) {
std:: cout<< "当前结点的值为" << bt- > data<< std:: endl;
}
void PreOrder ( BiTree bt) {
if ( bt== NULL )
return ;
Visit ( bt) ;
PreOrder ( bt- > lchild) ;
PreOrder ( bt- > rchild) ;
}
void InOrder ( BiTree bt) {
if ( bt== NULL )
return ;
InOrder ( bt- > lchild) ;
Visit ( bt) ;
InOrder ( bt- > rchild) ;
}
void PostOrder ( BiTree bt) {
if ( bt== NULL )
return ;
PostOrder ( bt- > lchild) ;
PostOrder ( bt- > rchild) ;
Visit ( bt) ;
}
Non-recursive version
void NRPreOrder ( BiTree bt) {
stack< BiTNode * > mystack;
mystack. push ( bt) ;
while ( ! mystack. empty ( ) ) {
BiTNode * top= mystack. top ( ) ;
mystack. pop ( ) ;
if ( top!= NULL ) {
Visit ( top) ;
mystack. push ( top- > rchild) ;
mystack. push ( top- > lchild) ;
}
}
}
void NRInOrder ( BiTree bt) {
stack< BiTNode * > mystack;
BiTNode * p= bt;
while ( p|| ! mystack. empty ( ) ) {
while ( p) {
mystack. push ( p) ;
p= p- > lchild;
}
p= mystack. top ( ) ;
mystack. pop ( ) ;
Visit ( p) ;
p= p- > rchild;
}
}
void NRPostOrder ( BiTree bt) {
stack< BiTNode * > mystack;
BiTNode * p= bt;
BiTNode * last= NULL ;
while ( p!= NULL || ! mystack. empty ( ) ) {
if ( p!= nullptr ) {
mystack. push ( p) ;
p= p- > lchild;
}
else {
p= mystack. top ( ) ;
if ( p- > rchild== nullptr || p- > rchild== last) {
Visit ( p) ;
mystack. pop ( ) ;
last= p;
p= nullptr ;
}
else {
p= p- > rchild;
}
}
}
}
Sequence traversal of queue implementation
void LevelOrder ( BiTree bt) {
queue< BiTNode * > myqueue;
if ( bt== nullptr )
return ;
myqueue. push ( bt) ;
while ( ! myqueue. empty ( ) ) {
BiTNode * p= myqueue. front ( ) ;
Visit ( p) ;
myqueue. pop ( ) ;
if ( p- > lchild!= nullptr ) {
myqueue. push ( p- > lchild) ;
}
if ( p- > rchild!= nullptr ) {
myqueue. push ( p- > rchild) ;
}
}
}