Two-tree sequential traversal, middle-sequence traversal and post-order traversal in combined mode

Source: Internet
Author: User
The basic concept of binary tree

In a computer, a binary tree is a tree structure that has a maximum of two subtrees per node. The subtree is often referred to as the left subtree and the right subtree (subtree).

A binary tree is a connected, loop-free graph, and the degree of each vertex is no more than 3. There is no more than 2 of the root node to be satisfied with a binary tree. With the root node, each vertex defines a unique parent node, and a maximum of 2 child nodes. However, there is not enough information to differentiate the left and right nodes.

Logically, there are five types of two-fork trees, such as:

    1. Empty binary Tree-(a);
    2. A two-fork tree with only one root node--(b);
    3. Only the left Dial hand tree-(c);
    4. Only right subtree-(d);
    5. Complete binary Tree-(e).

Terms related to Binary tree

    1. node of a tree: contains a data element and several branches pointing to subtrees;
    2. Child node: The root of the node's subtree is called the child of that node;
    3. Parent node: The b node is the child of a node, then the A node is the parent of the B node;
    4. Sibling node: child node of the same parent;
    5. Cousin node: Nodes on the same level;
    6. Ancestor node: All nodes from the root to the branch of the node
    7. Descendant nodes: Any node in a subtree that is rooted in a node is called a descendant of that node
    8. Node layer: The layer of the root node is defined as 1, the child of the root is the 2nd node, and so on;
    9. Tree Depth: The largest node layer in the tree
    10. Node Degree: The number of nodes in a tree
    11. The degree of the tree: the maximum node degree in the tree.
    12. Leaf node: Also known as an endpoint, is a node of degree 0;
    13. Branching node: Nodes with a degree of not 0;
    14. Ordered tree: A tree of ordered trees, such as: a family tree;
    15. Unordered tree: The order of the subtree is not considered;
Characteristics of Binary Tree
    1. In a non-empty binary tree, the total number of nodes in layer I does not exceed, i>=1;
    2. The two-fork tree with a depth of H has at most one node (h>=1), with a minimum of H nodes;
    3. For any binary tree, if its number of leaf nodes is N0, and the total number of nodes with a degree of 2 is N2, then n0=n2+1;
    4. The depth of a fully binary tree with N nodes is
    5. If the nodes of a complete binary tree with N nodes are stored sequentially, the nodes have the following relationship: If I is a node number, if i>1, then the number of its parent node is I/2, if 2*i<=n, then the number of its left son (that is, Zuozi root node) is 2*i; There is no left son; if 2*i+1<=n, the right son's node number is 2*i+1; if 2*i+1>n, there is no right son.
    6. Given n nodes, it can form an H (n) of different two-fork trees. H (n) is the nth item of the Cattleya number. H (N) =c (2*n,n)/(n+1).
    7. With I branch points, I is the sum of the road lengths of all branches, J is the sum of the road lengths of the leaves J=i+2i
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 accessed once, and only to be accessed 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.

Set L, D, R to Traverse Zuozi, access the root node, and traverse the right subtree, there are three scenarios for traversing a binary tree: The DLR (called the Sequential Traversal), LDR (called the Middle sequence Traversal), LRD (called the post-order traversal)

First Order Traversal (DLR):

First, the root is accessed, and then the left subtree is iterated, and the right subtree is iterated through the first sequence. As the result of the traversal is:ABCDE

Middle sequence Traversal (LDR):

First, the middle sequence traverses the left subtree, then accesses the root, and the final middle sequence traverses the right subtree, as the result of the traversal is:Cbdae

Post-post Traversal (LRD):

The first step is to traverse the left subtree, then go through the right sub-tree, and finally access the root. As the result of the traversal is: Cdbea

traditional recursive traversal of two-fork tree
 Public class node{public     Node (int i)    {        Data = i;    }     Public int Get set; } public    getset;}     Public Get set; Public    void Display (string lr)    {        Console.Write (lr + "" + Data);    }

First Order traversal

 Public void Dlrdisplay (Node thenode) {    ifnull)    {        thenode.display ("inorder");        Inorder (thenode.left);                      Inorder (thenode.right);    }}

Middle Sequence traversal

 Public void Ldrdisplay (Node thenode) {    ifnull)    {        inorder (thenode.left);                 Thenode.display ("inorder");                    Inorder (thenode.right);    }}

Post-post traversal

 Public void Lrddisplay (Node thenode) {    ifnull)    {               inorder (thenode.left);          Inorder (thenode.right);               Thenode.display ("inorder");}      }
Combined mode for three traversal of two-fork tree

Code implementation

 Public enumOrder {DLR,//First Order traversalLDR,//Middle sequence traversalLRD// post-traversal} Public Abstract classAbstracttreenode {protected stringName PublicAbstracttreenode (stringName) { This. name = name; } PublicAbstracttreenode Left {Get;Set; } PublicAbstracttreenode Right {Get;Set; } Public Abstract voidDisplay (order order); } Public classTreenode:abstracttreenode { PublicTreeNode (stringName):Base(name) { } Public Override voidDisplay (Order order) {Switch(order) { CaseORDER.DLR://D->l->rDlrdisplay (order); Break; CaseORDER.LDR://l->d->rLdrdisplay (order); Break; CaseORDER.LRD://l->r->dLrddisplay (order); Break; }        }Private voidDlrdisplay (Order order) {Console.Write (name);if(Left! =NULL) {Left.display (order); }if(Right! =NULL) {Right.display (order); }        }Private voidLdrdisplay (Order order) {if(Left! =NULL) {Left.display (order); } console.write (name);if(Right! =NULL) {Right.display (order); }                   }Private voidLrddisplay (Order order) {if(Left! =NULL) {Left.display (order); }if(Right! =NULL) {Right.display (order);                   } console.write (name); }    } Public classLeafnode:abstracttreenode { PublicLeafnode (stringName):Base(name) { } Public Override voidDisplay (Order order) {Console.Write (name); }    }

Test:

// <summary>// A///      /   \// B E///   /  \// C D// </summary>/// <param name= "args" ></param>Static voidMain (string[] args) {Abstracttreenode Roota, B, C, D, E; Roota =NewTreeNode ("A"); b =NewTreeNode ("B"); c =NewLeafnode ("C"); D =NewLeafnode ("D"); E =NewLeafnode ("E");    Roota.left = b;    Roota.right = e;     B.left = C;    B.right = D; Roota.display (ORDER.DLR);//OUTPUT->ABCDEConsole.WriteLine (); Roota.display (ORDER.LDR);//output->Cbdae Console.WriteLine (); Roota.display (ORDER.LRD);//output->cdbeaConsole.readkey ();}

Results:

Result of First order traversal: ABCDE

Results of the middle sequence traversal:Cbdae

Result of post-sequential traversal: Cdbea

In fact, it is possible to omit the leaf node class, just need an implementation of the class TreeNode, so it becomes simpler:

The code can be deleted Leafnode class, the client is only for TreeNode implementation. Because there is no management operation for complex branch nodes. Therefore, it is not necessary to treat branch nodes and leaf nodes separately.

 Public enumorder{DLR,//First Order traversalLDR,//Middle sequence traversalLRD// post-traversal} Public Abstract classabstracttreenode{protected stringName PublicAbstracttreenode (stringName) { This. name = name; } PublicAbstracttreenode Left {Get;Set; } PublicAbstracttreenode Right {Get;Set; } Public Abstract voidDisplay (Order order);} Public classtreenode:abstracttreenode{ PublicTreeNode (stringName):Base(name) { } Public Override voidDisplay (Order order) {Switch(order) { CaseORDER.DLR://D->l->rDlrdisplay (order); Break; CaseORDER.LDR://l->d->rLdrdisplay (order); Break; CaseORDER.LRD://l->r->dLrddisplay (order); Break; }    }Private voidDlrdisplay (Order order) {Console.Write (name);if(Left! =NULL) {Left.display (order); }if(Right! =NULL) {Right.display (order); }    }Private voidLdrdisplay (Order order) {if(Left! =NULL) {Left.display (order); } console.write (name);if(Right! =NULL) {Right.display (order); }               }Private voidLrddisplay (Order order) {if(Left! =NULL) {Left.display (order); }if(Right! =NULL) {Right.display (order);               } console.write (name); }}

Test:

// <summary>// A///      /   \// B E///   /  \// C D// </summary>/// <param name= "args" ></param>Static voidMain (string[] args) {Abstracttreenode Roota, B, C, D, E; Roota =NewTreeNode ("A"); b =NewTreeNode ("B"); c =NewTreeNode ("C"); D =NewTreeNode ("D"); E =NewTreeNode ("E");    Roota.left = b;    Roota.right = e;     B.left = C;    B.right = D; Roota.display (ORDER.DLR);//OUTPUT->ABCDEConsole.WriteLine (); Roota.display (ORDER.LDR);//output->Cbdae Console.WriteLine (); Roota.display (ORDER.LRD);//output->cdbeaConsole.readkey ();}

Results:

Result of First order traversal: ABCDE

Results of the middle sequence traversal:Cbdae

Result of post-sequential traversal: Cdbea

The results of the two tests were the same.

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.