The sequential storage structure of binary tree is to store the nodes in the binary tree with one-dimensional array, and the storage location of the nodes, that is, the subscript of the array, can reflect the logical relationship between the nodes. -–> is generally used only for complete binary trees
Chained storage-–> Two-fork list
Definition: lchild | Data | Rchild (two pointer fields, one data field)
typedefstruct Node { ElemType data; struct Node *lchild, *rchild;}BiTnode,* BiTree;
Note the point:
1) A binary tree can be uniquely identified by the pre-sequence traversal sequence and the middle sequence traversal sequence known
2) A binary tree can be uniquely identified by a sequence of sequential traversal and sequence traversal
and the pre-order and post-orders are known to be unable to determine a binary tree
two traversal of a fork tree: All nodes in the binary tree are accessed from the root node in a sequential order, so that each node is accessed once and accessed only once.
1. Pre-sequence traversal: root-left-right
Code:
PreOrder(BiTree T)/*先序遍历: 根-左-右*/{ if(T != NULL) { Visit(T); /*访问根节点*/ PreOrder(T->lchild); /*访问左子节点*/ PreOrder(T->rchild); /*访问右子节点*/ }}
2, Middle sequence traversal: left-root-right
Code:
InOrder(BiTree T)/*中序遍历:左-根-右*/{ if(T != NULL) { InOrder(T->lchild); //左 Visit(T); //根 InOrder(T->rchild); //右 }}
3, post-traversal: left-right-root
Code:
PostOrder(BiTree T)/*后序遍历:左-右-根*/{ if(T != NULL) { PostOrder(T->lchild); //左 PostOrder(T->rchild); //右 Visit(T); //根 }}
4, Sequence traversal: From the root node, access to the left and right children node, and then from the left and right children start, in turn their children node, until the end of the site access
Code: The program uses the idea of the queue, you can refer to the understanding
(the graph shows the breadth- first traversal of the graph, and applies the idea of sequence traversal )
/* Sequence traversal ideas: Each node is accessed from left to right sequentially, and the sequence traversal process requires a queue */voidLevelorder (Bitree t) {bitree p = t; queue<BiTree> Queue;/ * Queue * / Queue. push (P);/ * The root node is enqueued * / while(!Queue. empty ())/ * Queue not empty loop * /{p =Queue. Front ();/ * Enemy elements out of the team * / //printf ("%c", p->data); /* Access the node where p points * / cout<< P->data <<" ";Queue. Pop ();/ * Exit queue * / if(P->lchild! = NULL) {/ * Left dial hand tree is not empty, the left sub-tree queue * * Queue. push (P->lchild); }if(P->rchild! = NULL) {/ * Right subtree is not empty, the right sub-tree is enqueued * / Queue. push (P->rchild); } }}
/ drip accumulation, my small step O (∩_∩) o~/
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Binary Tree Traversal (plot)