Data Structure ---- binary tree traversal

Source: Internet
Author: User

I. Lab requirements

Binary tree traversal is the basis for many other operations in the tree structure. This experiment aims to help students further understand the features of binary tree traversal in ascending, central, and descending order, and familiarize themselves with the storage structure of binary linked lists, master the design technology of recursive algorithms on Binary Trees.


Ii. Lab questions

Construct a binary tree, store it using a binary linked list, design a program, and traverse the binary tree in three ways: First Order, middle order, and last order, recursive and non-recursive methods are required.


Iii. Implementation tips

1. Linear Linked List storage data structure of Binary Trees:


[Cpp]
Typedef char elemtype;
Typedef struct bitree {
Elemtype data;
Struct bitree * lchild, * rchild;
} BiTree;

2. Binary Tree construction method (reference ):

[Cpp]
BiTree * create ()
{
BiTree * q [100]; // defines the q array as a queue to store nodes in the binary linked list. The value 100 indicates the maximum capacity.
BiTree * s; // node in the binary linked list
BiTree * root; // root pointer of the binary linked list
Int front = 1, rear = 0; // defines the header and tail pointer of the queue.
Char ch; // The data field value of the node
Root = NULL;
Cin> ch;
While (ch! = '#') // The input value is #, and the algorithm ends.
{S = NULL;
If (ch! = ',') // The input data is not a comma, indicating that it is not a virtual node. Otherwise, it is a virtual node.
{S = new BiTree;
S-> data = ch;
S-> lchild = NULL;
S-> rchild = NULL;
}
Rear ++;
Q [rear] = s; // new node or virtual node enters the team
If (rear = 1)
Root = s;
Else
{If (s! = NULL) & (q [front]! = NULL ))
{If (rear % 2 = 0)
Q [front]-> lchild = s; // rear is an even number, and s is the left child of both parent
Else
Q [front]-> rchild = s; // The rear value is an odd number, and the s value is the right child of both parents.
}
If (rear % 2 = 1) front ++; // leaves
}
Cin> ch;
}
Return root;
}


4. Thinking and selection

1. This experiment provides a method to create a binary tree binary linked list storage structure. Is there a simpler method?

2. for non-recursive first-order traversal, it is generally necessary to perform a secondary stack for each node, which requires a flag. How to handle this flag, this eliminates the need to construct a new storage structure or add a new logo stack.


5. My implementation

[Cpp]
# Include <stdio. h>
# Include <stdlib. h>
# Include <iostream>
# Include <stack>
Using namespace std;

/******************* Data structure definition **************** *********/
Typedef char elemtype;
Typedef struct bitree
{
Elemtype data;
Struct bitree * lchild, * rchild;
} BiTree;


/********************** Function *************** ****************/
/*
Input Format: a (B, c (d, e ))
*/
BiTree * create (char * s, BiTree * & root)
{
Int I;
Bool isRight = false;
Stack <BiTree *> s1; // use the stack to store nodes.
Stack <char> s2; // delimiter
BiTree * p, * temp;
Root-> data = s [0];
Root-> lchild = NULL;
Root-> rchild = NULL;
S1.push (root );
I = 1;
While (I <strlen (s ))
{
If (s [I] = '(')
{
S2.push (s [I]);
IsRight = false;
}
Else if (s [I] = ',')
{
IsRight = true;
}
Else if (s [I] = ')')
{
S1.pop ();
S2.pop ();
}
Else if (isalpha (s [I])
{
P = (BiTree *) malloc (sizeof (BiTree ));
P-> data = s [I];
P-> lchild = NULL;
P-> rchild = NULL;
Temp = s1.top ();
If (isRight = true)
{
Temp-> rchild = p;
The right child of cout <temp-> data <"is" <s [I] <endl;
}
Else
{
Temp-> lchild = p;
The left child of cout <temp-> data <"is" <s [I] <endl;
}
If (s [I + 1] = '(')
S1.push (p );
}
I ++;
}
}
/*
Recursive printing function.
*/
Void display (BiTree * root)
{
If (root! = NULL)
{
Printf ("% c", root-> data );
If (root-> lchild! = NULL)
{
Printf ("(");
Display (root-> lchild );
}
If (root-> rchild! = NULL)
{
Printf (",");
Display (root-> rchild );
Printf (")");
}
}
}

/*
First traverse. Recursion.
*/
Void preOrder1 (BiTree * root)
{
If (root! = NULL)
{
Printf ("% c", root-> data );
PreOrder1 (root-> lchild );
PreOrder1 (root-> rchild );
}
}

/*
First traverse. Non-recursion.
1) Access Node P and add node P to the stack;
2) Determine whether the left child of node P is empty. If it is empty, take the top node of the stack and perform the out-of-stack operation, set the right child of the top node of the stack to the current node P and cycle to 1). If not empty, set the left child of P to the current node P;
3) The traversal ends until P is NULL and the stack is empty.
*/
Void preOrder2 (BiTree * root)
{
Stack <BiTree *> s; // you can also use arrays to implement
BiTree * p = root;
While (p! = NULL |! S. empty ())
{
While (p! = NULL)
{
Cout <p-> data <"";
S. push (p );
P = p-> lchild;
}
If (! S. empty ())
{
P = s. top ();
S. pop ();
P = p-> rchild;
}
}
}

/*
Traverse in the middle order. Recursion.
*/
Void inOrder1 (BiTree * root)
{
If (root! = NULL)
{
InOrder1 (root-> lchild );
Printf ("% c", root-> data );
InOrder1 (root-> rchild );
}
}

/*
Traverse in the middle order. Non-recursion.
1) if its left child is not empty, P is put into the stack and the left child of P is set to the current P, and then the current node P is processed in the same way;
2) If the left child of the stack is empty, the top element of the stack is taken and the stack is output, the top node of the stack is accessed, and the current P is set to the right child of the top node of the stack;
3) The traversal ends until P is NULL and the stack is empty;
*/
Void inOrder2 (BiTree * root)
{
Stack <BiTree *> s;
BiTree * p = root;
While (p! = NULL |! S. empty ())
{
While (p! = NULL)
{
S. push (p );
P = p-> lchild;
}
If (! S. empty ())
{
P = s. top ();
Cout <p-> data <"";
S. pop ();
P = p-> rchild;
}
}
}

/*
Post-order traversal. Recursion.
*/
Void postOrder1 (BiTree * root)
{
If (root! = NULL)
{
PostOrder1 (root-> lchild );
PostOrder1 (root-> rchild );
Printf ("% c", root-> data );
}
}

/*
Post-order traversal. Non-recursion.
Ensure that the root node can be accessed only after access by the left and right children. Therefore, for any node P, it is first written into the stack.
If P does not exist, you can directly access it; or P has left or right children,
If both the left and right children have been accessed, the node can also be accessed directly. If not,
Then P's right child and left child are added to the stack in sequence, which ensures that the left child is in the right child every time the top element of the stack is retrieved.
The child is accessed in front of the child, and both the left child and the Right child are accessed in front of the root node.
*/
Void postOrder2 (BiTree * root)
{
Stack <BiTree *> s;
BiTree * cur; // current node
BiTree * pre = NULL; // The Last accessed Node
S. push (root );
While (! S. empty ())
{
Cur = s. top ();
If (cur-> lchild = NULL & cur-> rchild = NULL) |
(Pre! = NULL & (pre = cur-> lchild | pre = cur-> rchild )))
{
Cout <cur-> data <"; // if the current node has no child node or the child node has been accessed
S. pop ();
Pre = cur;
} Www.2cto.com
Else
{
If (cur-> rchild! = NULL)
S. push (cur-> rchild );
If (cur-> lchild! = NULL)
S. push (cur-> lchild );
}
}

}

/************************ Main function ************** ***********/
Int main ()
{
Char s [100];
While (scanf ("% s", s )))
{
BiTree * root = (BiTree *) malloc (sizeof (BiTree ));
Create (s, root );
Printf ("\ n ");
Printf ("first-order recursive traversal :");
PreOrder1 (root );
Printf ("\ n ");
Printf ("sequential recursive traversal :");
InOrder1 (root );
Printf ("\ n ");
Printf ("recursive post-order traversal :");
PostOrder1 (root );
Printf ("\ n ");
Printf ("\ n ");
Printf ("sequential non-recursive traversal :");
PreOrder2 (root );
Printf ("\ n ");
Printf ("ordinal non-recursive traversal :");
InOrder2 (root );
Printf ("\ n ");
Printf ("post-Order Non-recursive traversal :");
PostOrder2 (root );
Printf ("\ n ");

}

Return 0;
}

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.