Algorithm of binary tree various traversal

Source: Internet
Author: User

Tree structure is a kind of important nonlinear data structure, in which tree and two-fork trees are most commonly used.

A binary tree is an ordered tree with a maximum of two subtrees per node. Usually the root of the subtree is referred to as the left subtree and right subtree. Binary trees are often used as binary search trees and two-fork or binary-ordered trees. Each node of a binary tree has a maximum of two subtrees trees (no nodes with a degree greater than 2), and the subtree of the binary tree has left and right points, and the order cannot be reversed. The first layer of the binary tree has a maximum of 2 i-1 nodes, and a two-tree with a depth of K has a maximum of 2^ (k)-1 nodes; for any binary tree T, if its terminal node number (that is, the leaf node number) is N0, the 2 node is n2, then N0 = n2 + 1.

The chain storage structure of binary tree is a kind of important data structure, and its form is defined as follows:

// two fork tree nodes struct bitnode{    // data    char  ;     // Child hands    left and right struct Bitnode *lchild,*rchild;} Bitnode,*bitree;

Binary Tree creation:

By reading a string, the algorithm for building a two-fork tree is as follows:

//create a two-fork tree by ordinal sequenceintCreatebitree (Bitree &T) {    Chardata; //Enter the value of the node in the binary tree in order of precedence (one character), ' # ' for the Empty treescanf"%c",&data); if(Data = ='#') {T=NULL; }    Else{T= (Bitree)malloc(sizeof(Bitnode)); //Generating root nodesT->data =data; //constructing the left sub-treeCreatebitree (t->lchild); //Constructing the right sub-treeCreatebitree (t->rchild); }    return 0;}

Traversal of a binary tree:

Traversal is one of the most basic operations of the tree, so-called traversal of the binary tree, that is, according to a certain rules and order all the nodes of the binary tree, so that each node is visited once, and only be visited once. Because the binary tree is a nonlinear structure, the traversal of the tree is essentially the transformation of each node of the two-fork tree into a linear sequence to be represented.

Recursive algorithm:

//OutputvoidVisit (Bitree T) {if(T->data! ='#') {printf ("%c",t->data); }}//First Order TraversalvoidPreorder (Bitree T) {if(T! =NULL) {        //Accessing the root nodeVisit (T); //access to left dial hand nodes.Preorder (t->lchild); //access to the right child nodePreorder (t->rchild); }}//Middle Sequence Traversalvoidinorder (Bitree T) {if(T! =NULL) {        //access to left dial hand nodes.Inorder (t->lchild); //Accessing the root nodeVisit (T); //access to the right child nodeInorder (t->rchild); }}//Post-post traversalvoidpostorder (Bitree T) {if(T! =NULL) {        //access to left dial hand nodes.Postorder (t->lchild); //access to the right child nodePostorder (t->rchild); //Accessing the root nodeVisit (T); }}

Non-recursive algorithm:

<1> first-order traversal:

"Thinking": After access to T->data, the t into the stack, traversing the left subtree, after traversing the Zuozi return, the top element of the stack should be T, out of the stack, and then sequentially traverse the right subtree of T.

/*First Order traversal (non-recursive) idea: After accessing the T->data, the t into the stack, traversing the left subtree, after traversing the Zuozi return, the top element of the stack should be T, out of the stack, and then first traversing the right subtree of T. */voidPreOrder2 (Bitree T) {stack<BiTree>Stack; //p is the traversal pointerBitree p =T; //stack is not empty or p is not empty when the loop     while(P | |!Stack.empty ()) {        if(P! =NULL) {            //deposited in the stackStack.push (P); //Accessing the root nodeprintf"%c",p->data); //traversing the left sub-treep = p->Lchild; }        Else{            //Back Stackp =Stack.top ();            Stack.pop (); //access to the right sub-treep = p->Rchild; }    }// while}

<2> in-sequence traversal

"Idea": T is to traverse the root of the tree pointer, the middle sequence traversal requires that after traversing the left dial hand tree, access to the root, and then traverse the right subtree.
First, the t into the stack, traversing the left subtree, after traversing the Zuozi return, the top element of the stack should be T, out of the stack, access to T->data, and then the right subtree of t traversal.

voidInOrder2 (Bitree T) {stack<BiTree>Stack; //p is the traversal pointerBitree p =T; //stack is not empty or p is not empty when the loop     while(P | |!Stack.empty ()) {        if(P! =NULL) {            //deposited in the stackStack.push (P); //traversing the left sub-treep = p->Lchild; }        Else{            //back up the stack, access the root nodep =Stack.top (); printf ("%c",p->data);            Stack.pop (); //access to the right sub-treep = p->Rchild; }    }// while}

<3> Post-traversal

"Thinking": T is to traverse the root of the tree pointer, post-order traversal requirements after traversing the left and right subtree, and then access to the root. It is necessary to determine whether the left and right subtrees of the root node have been traversed.

//Post -Post traversal (non-recursive)typedefstructbitnodepost{Bitree Bitree; Chartag;} Bitnodepost,*Bitreepost;voidPostOrder2 (Bitree T) {stack<BiTreePost>Stack; //p is the traversal pointerBitree p =T;    Bitreepost BT; //stack is not empty or p is not empty when the loop     while(P! = NULL | |!Stack.empty ()) {        //traversing the left sub-tree         while(P! =NULL) {BT= (bitreepost)malloc(sizeof(Bitnodepost)); BT->bitree =p; //visited left dial hand treeBt->tag ='L';            Stack.push (BT); P= p->Lchild; }        //Access to the root node after the left and right sub-tree access         while(!stack.empty () && (Stack.top ())->tag = ='R') {BT=Stack.top (); //Back StackStack.pop (); BT-Bitree; printf ("%c",bt->bitree->data); }        //traversing the right sub-tree        if(!Stack.empty ()) {BT=Stack.top (); //access to right sub-treeBt->tag ='R'; P= bt->Bitree; P= p->Rchild; }    }// while}

<4> Hierarchy Traversal

"Thinking": Each node is accessed hierarchically from top to bottom, from left to right, and the queue is used during the hierarchical traversal process.

//Hierarchical TraversalvoidLevelorder (Bitree T) {Bitree P=T; //QueueQueue<bitree>queue; //The root node is enqueuedQueue.push (P); //Queue not empty loop     while(!Queue.empty ()) {        //enemy elements out of the teamp =Queue.front (); //access the node to which P pointsprintf"%c",p->data); //Exit QueueQueue.pop (); //left dial hand tree is not empty, the left sub-tree to the queue        if(P->lchild! =NULL) {Queue.push (P-lchild); }        //right subtree is not empty, the right subtree is enqueued        if(P->rchild! =NULL) {Queue.push (P-rchild); }    }}

Algorithm of binary tree various traversal (turn)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.