Data Structure-binary tree traversal

Source: Internet
Author: User

Data Structure-binary tree traversal
Traversing a binary tree in ascending order

1 Recursive Algorithm
The recursive definition of an algorithm is:
If the binary tree is empty, the traversal ends. Otherwise
(1) traverse the left subtree In The Middle Order (recursively call this algorithm );
(2) access the root node;
(3) traverse the right subtree in ascending order (this algorithm is called recursively ).

Recursive Algorithm for sequential Traversal

Void InorderTraverse (BTNode * T) {if (T = NULL) return; InorderTraverse (T-> Lchild); visit (T-> data ); /* access the root node */InorderTraverse (T-> Rchild );}

2 Non-recursive algorithms (omitted)
If T is a pointer variable pointing to the root node of a binary tree, the non-recursive algorithm is:
If the binary tree is null, return. Otherwise, p = T
(1) When p is not empty, p is pushed to the stack, p = p-> Lchild;
(2) otherwise (p is empty), roll back to p and access the node pointed to by p;
(3) p = p-> Rchild, convert (1 );
Until the stack is empty.
Algorithm Implementation:

#define MAX_STACK_SIZE 50void InorderTraverse( BTNode *T){ BTNode *Stack[MAX_STACK_SIZE ] ,*p=T ; int top=0 , bool=1 ; if (T==NULL) printf(“ Binary Tree is Empty!\n”) ; else { do { while (p!=NULL) { stack[++top]=p ; p=p->Lchild ; } if (top==0) bool=0 ; else { p=stack[top] ; top-- ; visit( p->data ) ; p=p->Rchild ; } } while (bool!=0) ; } }
Post-order traversal of Binary Trees

1 Recursive Algorithm
The recursive definition of an algorithm is:
If the binary tree is empty, the traversal ends. Otherwise
(1) traverse the left subtree in descending order (this algorithm is called recursively );
(2) traverse the right subtree in descending order (this algorithm is called recursively );
(3) Access the root node.

Recursive Algorithm void PostorderTraverse (BTNode * T) {if (T! = NULL) {PostorderTraverse (T-> Lchild); PostorderTraverse (T-> Rchild); visit (T-> data ); /* access the root node */} basically accesses the node in the binary tree traversal algorithm. Therefore, no matter what order of traversal, for a binary tree with n nodes, the time complexity is O (n ).

2 Non-recursive algorithms (omitted)
In the post-order traversal, the root node is finally accessed. Therefore, in the traversal process, when the search Pointer Points to a root node, you cannot access it immediately. Instead, you need to traverse the left subtree first, and then the root node goes to the stack. When the left subtree is traversed and the root node is searched, it still cannot be accessed and needs to traverse its right subtree. Therefore, the root node needs to be re-added to the stack. After the right subtree is traversed, the node is moved back to the root node to be accessed.
Therefore, set a state flag variable tag:
Second, two storage nodes S1, S2, and S1 are set, and S2 stores the state flag variable tag of the node. S1 and S2 share a stack top pointer.
If T is a pointer variable pointing to the root node, the non-recursive algorithm is:
If the binary tree is empty, return; otherwise, p = T;
(1) do not access the root node p for the first time:
P into Stack S1, tag value 0, into Stack S2, p = p-> Lchild.
(2) If p is not blank, convert it to (1). Otherwise, take the status flag value tag:
(3) If tag = 0: no access to stack S1, no stack exists. Modify the element value (tag value 1) at the top of stack S2 to obtain the right subtree of the element at the top of stack S1, that is, p = S1 [top]-> Rchild, convert (1 );
(4) If tag = 1: S1, the node is accessed;
Until the stack is empty.

Algorithm Implementation: # define MAX_STACK_SIZE 50 void PostorderTraverse (BTNode * T) {BTNode * S1 [MAX_STACK_SIZE], * p = T; int S2 [MAX_STACK_SIZE], top = 0, bool = 1; if (T = NULL) printf ("Binary Tree is Empty! \ N "); else {do {while (p! = NULL) {S1 [++ top] = p; S2 [top] = 0; p = p-> Lchild;} if (top = 0) bool = 0; else if (S2 [top] = 0) {p = S1 [top]-> Rchild; S2 [top] = 1;} else {p = S1 [top]; top --; visit (p-> data); p = NULL;/* continue the loop instead of endless loops */} while (bool! = 0 );}}
Layered traversal Binary Tree
A layered traversal binary tree is used to traverse the root node and access each node in the tree from top to bottom and from left to right in hierarchical order. To ensure that the data is traversed by layers, a queue must be set. Set T to a pointer variable pointing to the root node. The non-recursive algorithm for layered traversal is:

If the binary tree is null, return. Otherwise, p = T and p are queued;
(1) The first element of the team goes to p;
(2) access the node pointed to by p;
(3) queue the left and right child nodes of the nodes pointed to by p. Until the team is empty.

# Define MAX_NODE 50 void LevelorderTraverse (BTNode * T) {BTNode * Queue [MAX_NODE], * p = T; int front = 0, rear = 0; if (p! = NULL) {Queue [++ rear] = p;/* Queue at the root node */while (front <rear) {p = Queue [++ front]; visit (p-> data); if (p-> Lchild! = NULL) Queue [++ rear] = p;/* enter the left node */if (p-> Rchild! = NULL) Queue [++ rear] = p;/* enter the left node */}}}
Application of binary tree traversal algorithm
"Traversal" is the most important basic operation of a binary tree and the basis of various other operations. Many other operations of a binary tree can be implemented through traversal. For example, you can create a binary tree storage structure, calculate the number of nodes of the Binary Tree, and obtain the depth of the binary tree.

The method to expand a binary tree is to add an extended node (always a leaf node, represented by the box "□") to each empty chain field of the node in the binary tree ). For the Binary Tree node value:
◆ Char type: the expanded node value is "?" Or "#";
◆ Int type: the expanded node value is 0 or-1;
The following algorithm is a recursive algorithm created in the forward direction of a binary tree. It reads the node value sequence in the forward direction of the Extended Binary Tree corresponding to a binary tree. Each time a node value is read, it is analyzed:
◆ If it is an extended node value: Make the root pointer NULL;
◆ If it is a (normal) node value: dynamically allocate a node to the pointer, assign the value to the root node, and then recursively create the left and right subtree of the root.

Algorithm Implementation: # define NULLKY '? '# Define MAX_NODE 50 typedef struct BTNode {char data; struct BTNode * Lchild, * Rchild;} BTNode; BTNode * Preorder_Create_BTree (BTNode * T)/* create a chain binary tree, returns the pointer variable */{char ch; ch = getchar (); if (ch = NULLKY) {T = NULL; return (T );} else {T = (BTNode *) malloc (sizeof (BTNode); T-> data = ch; Preorder_Create_BTree (T-> Lchild ); preorder_Create_BTree (T-> Rchild );}}
Calculate the number of leaf nodes of a binary tree

2. Calculate the number of leaf nodes of a binary tree.
You can use the first-order traversal binary tree algorithm to calculate the number of leaf knots of a binary tree. You can simply modify the vist () function in the first-order traversal binary tree algorithm.
Algorithm Implementation:

#define  MAX_STACK_SIZE 50int  BiTreeleaves( BTNode  *T){  BTNode  *stack[MAX_STACK_SIZE] ,*p=T;int  top=0, num=0;if  (T!=NULL){  stack[++top]=p ; while (top>0)   {  p=stack[top--] ;       if (p->Lchild==NULL&&p->Rchild==NULL)  num++ ;           if  (p->Rchild!=NULL )             stack[++top]=p->Rchild;         if  (p->Lchild!=NULL )                stack[++top]=p->Lchild;      }}return(num) ;}
Binary Tree depth

3. determine the depth of a binary tree
The depth of a binary tree can be directly obtained using the hierarchical traversal algorithm.
Algorithm Implementation:

# Define MAX_NODE 50int BiTreedepth (BTNode * T) {BTNode * Queue [MAX_NODE], * p = T; int front = 0, rear = 0, depth = 0, level; /* level always points to the position of the last node of the access layer in the queue */if (T! = NULL) {Queue [++ rear] = p;/* enter the root node */level = rear; /* The root node is the last node in Layer 3 */while (front <rear) {p = Queue [++ front]; if (p-> Lchild! = NULL) Queue [++ rear] = p;/* enter the left node */if (p-> Rchild! = NULL) Queue [++ rear] = p;/* enter the left node */if (front = level) /* The Last node of the current layer is being accessed */{depth ++; level = rear ;}}}}
Recursive Algorithms for depth
/* Initial condition: binary tree T exists. Operation Result: returns the depth of T */int BiTreeDepth (BiTree T) {int I, j; if (! T) return 0; if (T-> lchild) I = BiTreeDepth (T-> lchild); else I = 0; if (T-> rchild) j = BiTreeDepth (T-> rchild); else j = 0; return I> j? I + 1: j + 1 ;}

Related Article

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.