Data Structure and algorithm (Binary Tree)

Source: Internet
Author: User
Binary Tree Storage Structure

Binary Tree storage can be divided into two types: sequential Storage Structure and chained storage structure.

1.Sequential Storage Structure

The numbers of a full binary tree are sequentially numbered from top to bottom and from left to right in the array. The result shown in Figure 6.8 (a) is displayed. If the index number of the full Binary Tree node in the array is I, it has the following properties.

(1) If I = 0, this node is the root node and has no parent nodes.

(2) If I> 0, the parent node is (I-1)/2. (Note that the division here is division, and the fractional part in the result will be discarded .)

(3) The left child of node I is 2I + 1, and the right child is 2I + 2.

(4) If I> 0, When I is an odd number, it is the left child of the parent node, and its brother is I + 1; when I is an even number, it is the right child of a dual-node, and its brother node is I-1.

(5) the depth of K full binary tree needs to be 2 K-1 array for storage.

The above properties show that it is very convenient to store nodes full of Binary trees using arrays. You can easily calculate the numbers of nodes such as parent, child, and brother Based on the index number of a node, to access these nodes, This is the simplest and most spatial method to store binary full or full Binary Trees.

In order to reflect the logical relationship between nodes by using the location of nodes in the array, when storing Binary Trees, you only need to set the location of the empty nodes in the array to null, the effect is shown in Figure 6.8 (B. This will cause a certain amount of space waste, but if the number of empty nodes is not large, these waste can be ignored.

A depth of K binary tree needs 2 K-1 storage space, when the K value is very large and a lot of empty nodes of the binary tree, the worst case is that each layer has only one node, using the sequential storage structure to store data is obviously a huge waste. In this case, we should use a chain storage structure to store data in Binary Trees.



 

1.Chained Storage Structure

The chain storage structure of a binary tree can be divided into two linked lists and three linked lists. In a binary linked list, each node not only stores its own data, but also sets two pointer fields left and right, respectively pointing to the left and right children (6.9 ().

When you need to find the parent of a node in a binary tree, you can add a pointer domain parent pointing to the parent, as shown in 6.9 (B.



 

Figure 6.10 shows the storage structure of the binary linked list and the triplicate linked list. The dotted arrow indicates the direction indicated by the parent pointer.



 

The binary tree also has a storage structure called the Parent-Child linked list. It only stores the Parent-Child Information of the node instead of the Child Information. Because the binary tree is an ordered tree, the two children at a node have left and right points. Therefore, in addition to storing the new information, the node must also specify whether the node is left or right. Because the node does not store the Child Information, it cannot traverse all nodes through the header pointer. Therefore, you need to store the node information through arrays. The binary tree shown in Figure 6.10 (a) is stored with a parent linked list. The result shown in Figure 6.11 is displayed. Because the root node does not have a new pair, the value of its parent pointer is set to-1.



 

The order in which elements are stored in the parent linked list is determined by the order of adding nodes. That is to say, changing the storage locations of each element does not affect the logical structure of the nodes. As shown in figure 6.11, the parent-parent linked list is physically a sequential storage structure.

A binary tree has multiple storage structures. The method used for storage depends on the operations performed on the binary tree. The binary linked list is the most commonly used storage structure of Binary Trees. The algorithms related to binary trees in the following sections are mostly based on the binary linked list storage structure.

6.3 binary tree traversal

A binary tree traversal (traversal) is a process that accesses each node in the tree in a certain order and can only be accessed once. Access has a wide range of meanings, such as query, calculation, modification, and output node values. In essence, tree traversal is the linearity of non-linear structures. It is the basis for the implementation of various operations and operations on Binary Trees and requires great attention.

6.3.1 Binary Tree depth-first Traversal

 

Figure 6.12 recursive definition of a binary tree

 

D

 

L

 

R

We use recursive methods to define Binary Trees. Each binary tree consists of three basic parts: node, left subtree, and right subtree. If these three parts are traversed, the entire binary tree is traversed. As shown in 6.12, D is a node of a binary tree, and l and R are left and right subtree of node d, respectively. There are 6 traversal methods:

 

First left, right first right then left

First-order DLR DRL

Middle-order LDR RDL

LRD RLD

Here we will only discuss three Traversal Algorithms: First left and then right.
 

As shown in 6.13, the binary tree is traversed by following the path indicated by the arrow. Each node appears three times in this search path, and the access operation can only be performed once, in this case, it is necessary to determine the first nodes in the search path for access operations, which leads to three different Traversal Algorithms.



 

1.First-order traversal

If the binary tree is not empty, the process is:

(1) access the root node.

(2) traverse the left subtree in sequence.

(3) traverse the right subtree in sequence.

In Figure 6.13, the first-order traversal is to connect the nodes marked as (1) by the order of Access to the search path. The result is abdecf.

2.Sequential Traversal

If the binary tree is not empty, the process is:

(1) traverse the left subtree in the middle order.

(2) access the root node.

(3) traverse the right subtree in the middle order.

In Figure 6.13, the first order traversal is to connect the nodes marked as (2) by the order of Access to the search path. The result is: dbeacf.

3.Post-order traversal

If the binary tree is not empty, the process is:

(1) traverse the left subtree in descending order.

(2) traverse the right subtree in descending order

(3) Access the root node.

In Figure 6.13, the first order traversal is to connect the nodes marked as (3) according to the order of Access to the search path. The result is: debfca.

 

Using system; using system. collections. generic; namespace net. MST. thirteenth. binarytree {class mainclass {// <summary> // test the binary tree, and perform sequential and post-sequential traversal. /// </Summary> static void main (string [] ARGs) {int [] DATA = new int [] {6, 1, 3, 9, 2, 7, 11}; binarytree root = binarytree. generatebinarytree (data); console. write ("sequential traversal:"); root. inorder (); console. write ("\ r \ n"); console. write ("sequential traversal:"); root. lastorder (); cons Ole. write ("\ r \ n"); console. read ();}} /// <summary> /// binary tree implementation /// </Summary> partial class binarytree {// left subtree pointer private binarytree _ left = NULL; // The right subtree pointer private binarytree _ Right = NULL; // The value of the node. Here, an integer is used to indicate private int _ value; // <summary> // The constructor, left and right subtree is set to null // </Summary> /// <Param name = "Val"> node value </param> Public binarytree (INT Val) {_ value = Val ;}/// <summary> /// constructor /// </Summary> /// <Param Name = "Val"> node value </param> /// <Param name = "Left"> left subtree pointer </param> /// <Param name = "right"> right subtree pointer </param> Public binarytree (INT Val, binarytree left, binarytree right) {_ value = val; _ left = left; _ Right = right;} // read/write attribute public binarytree left {get {return _ left ;} set {_ left = value ;}} public binarytree right {get {return _ Right;} set {_ Right = value ;}} public int value {get {return _ valu E ;}set {_ value = value ;}}} /// <summary> /// Binary Tree Generation and insertion /// </Summary> partial class binarytree {// <summary> // The static method is used from an array generate a binary tree // This uses ordered inserts // </Summary> /// <Param name = "data"> input array </param> // /<returns> return the root node </returns> Public static binarytree generatebinarytree (INT [] data) {// ensure that the array is not empty if (data. length <= 0) return NULL; // generate the root node binarytree root = new binarytree (data [0]); // ensure that the Left subtree needs to be generated Or the right subtree if (data. length <= 1) return root; // Insert the entire array one by one for (INT I = 1; I <data. length; I ++) root. insertelement (data [I]); Return root;} // <summary> // Insert elements in sequence, the result of insertion is that the binary tree can be traversed in the middle order to obtain an ordered sequence // </Summary> /// <Param name = "Val"> value to be inserted </param> Public void insertelement (INT Val) {// If (Val <= _ value) needs to be inserted in the left subtree {// The left subtree is empty, and the new element if (_ left = NULL) needs to be inserted) {binarytree node = new binarytree (VAL); _ left = node;} // left child Tree is not empty, recursive else _ left. insertelement (VAL);} // else needs to be inserted in the right subtree {// The right subtree is empty and the new element if (_ Right = NULL) needs to be inserted) {binarytree node = new binarytree (VAL); _ Right = node;} // The right subtree is not empty. Recursive else _ right. insertelement (VAL );}}} /// <summary> /// traverse a binary tree /// </Summary> partial class binarytree {// <summary> /// traverse a binary tree in the middle order /// </Summary> Public void inorder () {// use the recursive algorithm if (_ left! = NULL) _ left. Inorder (); console. Write ("{0},", _ value); If (_ right! = NULL) _ right. inorder () ;}//< summary> /// post-order traversal of Binary Trees /// </Summary> Public void lastorder () {// use the recursive algorithm if (_ left! = NULL) _ left. lastorder (); If (_ right! = NULL) _ right. lastorder (); console. Write ("{0},", _ value );}}}

 

 

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.