Binary tree traversal, in-depth solution, and vertical print details

Source: Internet
Author: User

A binary tree is an ordered tree with a maximum of two Subtrees. Binary Tree is often used to implement binary search tree and binary heap. It is worth noting that a binary tree is not a special case of a tree. In graph theory, a binary tree is a connected acyclic graph, and the degree of each vertex is not greater than 2. If a binary tree has a root node, the degree of root node must not exceed 2. With the root node, each vertex defines a unique root node and a maximum of two subnodes. However, there is not enough information to distinguish the Left and Right nodes. For details about Binary Trees, see this article: Binary Trees


The so-called traversal (traversal) refers to the sequential access to each node in the tree along a certain search route. The operations performed by the Access Node depend on specific application questions. Traversal is one of the most important operations on Binary Trees and is the basis for other operations on Binary Trees.

The Code is as follows:

# Include <iostream> # include <cstdlib> using namespace STD; typedef char elemtype; typedef struct node {elemtype data; struct node * lchild; struct node * rchild;} bitnode, * bitree; int leafcount; int depth; void visit (elemtype t) // output for traversal {cout <t ;}// 1. create a binary tree void createbitree (bitree * BT) {char ch; CH = getchar (); If (CH = '. ') * bt = NULL; else {* bt = (bitree) malloc (sizeof (bitnode); // generate a new node (* BT)-> DATA = CH; createbitree (&((* BT)-> lchild); // generate the left subtree createbitree (& (* BT)-> rchild); // generate the right subtree} // 2. binary tree traversal void preorder (bitree root)/* First traverse Binary Tree, root is the pointer to the root node of a binary tree (or a subtree) */{If (root! = NULL) {visit (root-> data);/* access the root node */preorder (root-> lchild ); /* traverse the left subtree first */preorder (root-> rchild);/* traverse the right subtree first */} elsecout <". ";} void inorder (bitree root)/* traverses Binary Trees in ascending order. Root is the pointer to the root node of a binary tree (or a subtree) */{If (root! = NULL) {inorder (root-> lchild);/* traverse the left subtree In The Middle Order */visit (root-> data ); /* access the root node */inorder (root-> rchild);/* traverse the right subtree In The Middle Order */} elsecout <". ";} void postorder (bitree root)/* traverses Binary Trees sequentially. Root is the pointer to the root node of a binary tree (or a subtree) */{If (root! = NULL) {postorder (root-> lchild);/* traverse the left subtree in descending order */postorder (root-> rchild ); /* traverse the right subtree in descending order */visit (root-> data);/* access the root node */} elsecout <". ";} // 3. the "leaf" node on the output binary tree (three methods, only the first order is written. For details, refer to the previous 2. binary tree traversal) void leafpreorder (bitree root)/* traverses Binary Trees sequentially. Root is the pointer to the root node of the binary tree */{If (root! = NULL) {If (root-> lchild = NULL & root-> rchild = NULL) visit (root-> data ); /* output leaf node */preorder (root-> lchild);/* traverse the left subtree first */preorder (root-> rchild ); /* First traverse the right subtree */} // 4. count the number of leaf nodes (two methods)/* leafcount to save the global variable of the number of leaf nodes. The initial value before the call is 0 */void leaf_a (bitree root) // Method for counting the number of leaf nodes: 1 {If (root! = NULL) {leaf_a (root-> lchild); leaf_a (root-> rchild); If (root-> lchild = NULL & root-> rchild = NULL) leafcount ++ }}int leaf_ B (bitree root) // Method for counting the number of leaf nodes 2 {int leafcount2; If (root = NULL) leafcount2 = 0; else if (root-> lchild = NULL) & (root-> rchild = NULL) leafcount2 = 1; else leafcount2 = leaf_ B (root-> lchild) + leaf_ B (root-> rchild);/* sum of the number of leaves on the left and right subtree */return leafcount2;} // 6. calculate the height recursion algorithm int posttreedepth (bitree BT) of a binary tree by post-sequential Traversal) {Int HL, HR, Max; If (BT! = NULL) {HL = posttreedepth (BT-> lchild);/* evaluate the depth of the Left subtree */HR = posttreedepth (BT-> rchild ); /* Find the depth of the right subtree */max = HL> HR? Hl: HR;/* the person with a large left and right subtree depth */Return (MAX + 1);/* return tree depth */} else return (0 ); /* if it is an empty tree, 0 */} // 6 is returned. the height recursion algorithm void pretreedepth (bitree BT, int h)/* the former traverses the height of the Binary Tree Bt. h indicates the hierarchy where BT points to the node, the initial value is 1 * // * depth, which is the maximum level currently obtained and a global variable. The initial value before the call is 0 */{If (BT! = NULL) {If (h> depth) depth = H;/* If the hierarchical value of the node is greater than depth, update the value of depth */pretreedepth (BT-> lchild, H + 1);/* traverse the left subtree */pretreedepth (BT-> rchild, H + 1);/* traverse the right subtree */}/7. "vertical" Print Binary Tree void printtree (bitree BT, int nlayer)/* print Binary Tree by vertical tree */{If (bt = NULL) return; printtree (BT-> rchild, nlayer + 1); For (INT I = 0; I <nlayer; I ++) printf (""); printf ("% C \ n", BT-> data); printtree (BT-> lchild, nlayer + 1);} int main () {leafcount = 0; depth = 0; bitree T = NULL; cout <"Please input a binary tree in the form of first-order output to construct a binary linked list:" <Endl; createbitree (& T ); cout <"first-order traversal of a binary tree is:" <Endl; preorder (t); cout <Endl <"middle-order traversal of a binary tree is:" <Endl; inorder (t); cout <Endl <"post-order traversal Binary Tree:" <Endl; postorder (t ); cout <Endl <"the first-order output binary tree leaf node is:" <Endl; leafpreorder (t); cout <Endl <"the number of leaf nodes is: "<Endl; leaf_a (t); cout <Endl <" method 1 shows a total of "<leafcount <" leaf nodes "<Endl; cout <Endl <"method 2 shows a total of" <leaf_ B (t) <"leaf nodes" <Endl; cout <Endl <"the height of the Binary Tree obtained by post-sequential traversal is" <posttreedepth (t) <Endl; pretreedepth (T, 1 ); cout <Endl <"the height of the Binary Tree obtained by preorder traversal is" <depth <Endl; cout <Endl <"the vertical print binary tree is: "<Endl; printtree (T, 1); Return 0 ;}

Non-recursive algorithms with binary tree traversal:

/* Post-non-recursive traversal of the binary tree as a reference for the Traversal method * // 8. in-order traversal of Binary Tree non-recursive algorithms (three)/* algorithm A */void inorder (bitree root); {int Top = 0; P = Bt; L1: If (P! = NULL)/* traverse the left subtree */{Top = Top + 2; If (top> m) return; /* stack overflow handling */s [Top-1] = P;/* introduce the parameters of the current layer into the stack */s [Top] = L2; /* return address to stack */P = p-> lchild;/* assign a value to the lower-layer parameter */goto L1;/* Start of redirection */L2: visit (p-> data);/* access root */Top = Top + 2; If (top> m) return;/* stack overflow handling */; s [Top-1] = P;/* traverse the right subtree */s [Top] = l3; P = p-> rchild; goto L1;} L3: if (top! = 0) {ADDR = s [Top]; P = s [Top-1];/* retrieve the return address */Top = Top-2; /* exit the current layer parameter */goto ADDR;}/* algorithm B */void inorder (bitree root)/* traverse the binary tree in ascending order, root is the root node of the binary tree */{int Top = 0; bitree P; bitree s [stack_size]; int m; M = Stack_Size-1; P = root; do {While (P! = NULL) {If (top> m) return; Top = Top + 1; s [Top] = P; P = p-> lchild ;}; /* traverse the left subtree */If (top! = 0) {P = s [Top]; Top = Top-1; visit (p-> data);/* access the root node */P = p-> rchild; /* traverse the right subtree */} while (P! = NULL | top! = 0);}/* algorithm C */void inorder (bitree root)/* Non-recursive algorithm for Traversing binary trees in the central order */{seqstack s; bitree P; initstack (& S); P = root; while (P! = NULL |! Isempty (& S) {If (P! = NULL)/* The root pointer goes into the stack and traverses the left subtree */{push (& S, P); P = p-> lchild ;} else {/* The root pointer goes back to the stack, accesses the root node, and traverses the right subtree */POP (& S, & P); visit (p-> data ); P = p-> rchild ;}}// 9. void postorder (bitree root) {bitnode * P, * q; bitnode ** s; int Top = 0; q = NULL; P = root; S = (bitnode **) malloc (sizeof (bitnode *) * num);/* num is a predefined constant */while (P! = NULL | top! = 0) {While (P! = NULL) {top ++; s [Top] = P; P = p-> lchild;}/* traverse the left subtree */If (top> 0) {P = s [Top]; If (P-> rchild = NULL) | (p-> rchild = q)/* No right child, or the right child has traversed */{visit (p-> data);/* access the root node */q = P;/* save it to Q, is the precursor to the next processed node */top --; P = NULL;} elsep = p-> rchild;} Free (s );}




Binary tree traversal, in-depth solution, and vertical print details

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.