Before I read a book to write a binary tree, now seems to write almost fraught ... So deleted, decided to write a re-article.
Binary tree: About the learning process of binary tree The most profound is that you want to learn the two-fork tree, then the premise you have to master the mastery of recursion, so that recursion for the binary tree is very important.
About the node structure of binary tree, need a data field, two pointer field
typedef struct BTNODE
{
Btnode *leftchild;
Btnode *rightchild;
Elemtype data;
}btnode, * BinaryTree;
The structure initialization and release of the nodes of a binary tree direct reference to the malloc,free of the linked list is good.
Here is a way to construct a two-fork tree in the first order, but it is important to set the node end flag in advance.
typedef char ELEMTYPE;
#define END ' # '
The string is then used to represent, for example str= "ab# #C # #" constructed to
A
B C
Recursive construction
Btnode * Create (elemtype *&str)
{
Btnode *s = NULL;
if (*str! = END)
{
s = _buynode ();
S->data = *str;
S->leftchild = Create (++STR);
S->rightchild = Create (++STR);
}
return s;
}
Btnode *createtree (Elemtype *str)
{
if (str = = NULL)
return NULL;
Else
return Create (str);
}
A test output function (first order output) is given.
void preorder (Btnode *p)//x first-order traversal
{
if (P! = NULL)
{
cout<<p->data<< "";
Preorder (P->leftchild);
Preorder (P->rightchild);
}
}
So the basic structure is complete, about the binary tree there are many many functions we need to implement, too much I will not write
A binary tree consists of three basic elements: the root node, the left subtree, and the right subtree.
L means traverse Zuozi
D means access to the root node
R means traversing the right sub-tree
We limit the left to the right, only three cases left.
First (root) sequence traversal:
(1) Accessing the root node
(2) First Order traversal Zuozi
(3) First order traversal of right sub-tree
Middle (Root) sequence traversal:
(1) Middle sequence traversal Zuozi
(2) Access to root node
(3) The middle sequence traverses the right sub-tree
Post (root) sequence traversal:
(1) post-Zuozi traversal
(2) to traverse the right sub-tree
(3) Access to root node