[Data structure and algorithm] JavaScript implements tree structure

1. Introduction to tree structure

1.1. Briefly understand the tree structure

What is a tree?

Real tree:

Insert image description here

Characteristics of the tree:

  • Trees generally have oneroot, connected to the root is thetrunk< a i=4>;
  • The trunk will bifurcate, forming manybranches, and the branches will continue to differentiate into smaller ones branches;
  • The end of the branch isleaf;

Many structures in real life are abstractions of trees, and the simulated tree structure is equivalent to a rotated 180° tree.

Insert image description here

What are the advantages of tree structures compared to arrays/linked lists/hash tables:

Array:

  • Advantages: Can be accessed through subscript value, high efficiency;
  • Disadvantage: When searching for data, you need to sort the data first and generate ordered array a>; displacement operations are required, in order to improve the search efficiency; and when inserting and deleting elements, a large number of

Linked list:

  • Advantages: Data insertion and deletion operations are very efficient;
  • Disadvantages:Search is inefficient, you need to search sequentially from the beginning until you find the target data; when you need to insert or delete in the middle of the linked list When inserting or deleting data, the efficiency is not high.

Hash table:

  • Advantages: The insertion/query/deletion efficiency of the hash table is very high;
  • Disadvantages:The space utilization rate is not high, many units in the underlying array are not used; and the elements in the hash table are Unordered, the elements in the hash table cannot be traversed in a fixed order; and the elements in the hash table cannot be quickly found Maximum or minimum valueThese special values.

Tree structure:

Advantages: The tree structure combines the advantages of the above three structures, and also makes up for their shortcomings (although the efficiency is not necessarily higher than them). For example, the data in the tree structure are ordered, and the search efficiency is high; space utilization High; and can quickly obtain the maximum and minimum values, etc.

In general:Each data structure has its own specific application scenarios

Tree structure:

  • Tree: A finite set composed of n (n ≥ 0) nodes . When n = 0, it is calledempty tree.

For any non-empty tree (n > 0), it has the following properties:

  • There is a special node in the number calledRoot, which is represented by r means;
  • The remaining nodes can be divided into m (m > 0) mutually disjoint finite sets T1, T2,..., Tm, where each set itself is a tree, called the original tree. SubTree

Common terms for trees:

Insert image description here

  • Degree of the node (Degree): The number of subtrees of the node, such as node B Degree is 2;
  • The degree of the tree: The largest degree of all nodes in the tree, as shown in the figure above. is 2;
  • Leaf node (Leaf):Node with degree 0 (also called leaf node) , such as H, I, etc. in the above picture;
  • Parent node (Parent): A node with a degree other than 0 is called a parent node. As shown in the figure above, node B is the parent node of nodes D and E;
  • Child node (Child): If B is the parent node of D, then D is the child node of B;
  • Sibling node (Sibling): Nodes with the same parent node are sibling nodes of each other, such as B and C, D and E in the above figure are sibling nodes of each other; a>
  • Path and path length: The path refers to the channel from one node to another node. The number of edges contained in the path is called the path length, such as A->H The path length is 3;
  • Node level (Level): stipulates that the root node is on level 1, and any other node The layer number is the layer number of its parent node plus 1. For example, the level of nodes B and C is 2;
  • Depth of the tree (Depth): The maximum level among all the nodes of the tree species is this tree The depth of the tree in the figure above is 4;
1.2. Representation of tree structure
  • The most common representation method:

Insert image description here

As shown in the figure, the tree structure is similar to a linked list, and is composed of nodes connected one by one. However, depending on the number of child nodes of each parent node, the number of references required by each parent node is also different. For example, node A needs 3 references, pointing to child nodes B, C, and D respectively; node B needs 2 references, pointing to child nodes E and F respectively; node K does not need references because it has no child nodes.

The disadvantage of this method is that we cannot determine the number of references to a certain node.

  • Son-brother notation:

Insert image description here

This representation method can completely record the data of each node, such as:

//节点A
Node{
    
    
  //存储数据
  this.data = data
  //统一只记录左边的子节点
  this.leftChild = B
  //统一只记录右边的第一个兄弟节点
  this.rightSibling = null
}

//节点B
Node{
    
    
  this.data = data
  this.leftChild = E
  this.rightSibling = C
}

//节点F
Node{
    
    
  this.data = data
  this.leftChild = null
  this.rightSibling = null
}

The advantage of this representation is that the number of references in each node is determined.

  • Son-brother representation rotation

The following is a tree structure composed of son-brother notation:

Insert image description here

After rotating it 45° clockwise:

Insert image description here

This becomes abinary tree, from which we can conclude:Any tree All can be simulated through binary trees. But doesn’t the parent node change in this way? In fact, the setting of the parent node is just to facilitate pointing to the child node. It does not matter who is the parent node in the code implementation, as long as the corresponding node can be found correctly.

2. Binary tree

2.1. Introduction to binary trees

The concept of a binary tree: If each node in the tree can only have at most two child nodes , such a tree is calledbinary tree;

Binary trees are very important, not only because of their simplicity, but also because almost all trees can be expressed in the form of binary trees.

Forked tree composition

  • A binary tree can be empty, that is, it has no nodes;
  • If the binary tree is not empty, it consists of the root node and two disjoint binary trees called its left subtree TL and right subtree TR;

Five forms of binary trees:

Insert image description here

The above figures respectively represent: an empty binary tree, a binary tree with only one node, a binary tree with only left subtree TL, a binary tree with only right subtree TR, and a binary tree with two left and right subtrees.

Characteristics of binary trees:

  • The maximum node tree at level i of a binary tree is: 2(i-1), i >= 1;
  • The maximum total number of nodes of a binary tree with depth k is: 2k - 1, k >= 1;
  • For any non-empty binary tree, if n0 represents the number of leaf nodes and n2 represents the number of non-leaf nodes with degree 2, then the two satisfy the relationship: n0 = n2 + 1; as shown in the following figure: H, E, I, J, G are leaf nodes, the total number is 5; A, B, C, F are non-leaf nodes with degree 2, the total number is 4; satisfy the rule of n0 = n2 + 1.

Insert image description here

2.2. Special binary tree

perfect binary tree

A Perfect Binary Tree also becomes a Full Binary Tree. In a binary tree, except for the leaf nodes at the lowest level, each node has 2 child nodes, which constitutes a perfect binary tree.

Insert image description here

complete binary tree

Complete Binary Tree:

  • Except for the last level of the binary tree, the number of nodes in all other levels has reached the maximum value;
  • Moreover, the leaf nodes of the last layer exist continuously from left to right, and only a few leaf nodes on the right are missing;
  • A perfect binary tree is a special complete binary tree;

Insert image description here

In the above figure, since H is missing the right child node, it is not a complete binary tree.

2.3. Binary tree data storage

Common binary tree storage methods arearray and linked list :

Use arrays:

  • Complete binary tree: Store data from top to bottom and from left to right.

Insert image description here

node A B C D AND F G H
serial number 1 2 3 4 5 6 7 8

When using array storage, it is also very convenient to retrieve data: the serial number of the left child node is equal to the serial number of the parent node * 2, and the serial number of the right child node is equal to the serial number of the parent node * 2 + 1.

  • Non-complete binary tree: An incomplete binary tree needs to be converted into a complete binary tree before it can be stored according to the above scheme, which will waste a lot of storage space.

Insert image description here

node A B C ^ ^ F ^ ^ ^ ^ ^ ^ M
serial number 1 2 3 4 5 6 7 8 9 10 11 12 13

Use linked list

The most common storage method of binary trees islinked list: each node is encapsulated into a Node, and the Node contains the stored data and the left node's reference and the reference of the right node.

Insert image description here

3. Binary search tree

3.1. Understand binary search trees

Two-pronged search treeBST, Binary Search Tree)、也为. Forked 查找树Forked order 树

A binary search tree is a binary tree and can be empty;

If it is not empty, then the followingproperty is satisfied:

  • Condition 1: Allkey values of the non-empty left subtree are less than< a i=4>The key value of its root node. For example, the key values ​​of all non-empty left subtrees of node 6 in the third node are less than 6;
  • Condition 2: Allkey values of the non-empty right subtree are greater than< a i=4>The key value of its root node; for example, the key values ​​of all non-empty right subtrees of node 6 in the third node are greater than 6;
  • Condition 3: The left and right subtrees themselves are also binary search trees;

Insert image description here

As shown in the figure above, tree two and three meet three conditions and belong to binary trees. Tree one does not meet condition three, so it is not a binary tree.

Summary:The main characteristics of binary search trees are thatsmaller values are always stored in On the left node, the larger value relative to is always saved in < /span>. This feature makes the query efficiency of binary search trees very high, which is the source of "search" in binary search trees. On the right node

3.2. Binary search tree application examples

Below is a binary search tree:

Insert image description here

If you want to find data 10 in it, you only need to search 4 times, and the search efficiency is very high.

  • The first time: Compare 10 with root node 9. Since 10 > 9, 10 is compared with the right child node 13 of root node 9 in the next step;
  • The 2nd time: Since 10 < 13, the next step of 10 is compared with the left child node 11 of the parent node 13;
  • The third time: Since 10 < 11, the next step of 10 is compared with the left child node 10 of the parent node 11;
  • The 4th time: Since 10 = 10, the data 10 is finally found.

Insert image description here

There are also 15 pieces of data. To query data 10 in the sorted array, you need to query 10 times:

Insert image description here

Actually: If it is a sorted array, you can use binary search: find 9 the first time, 13 the second time, 15 the third time... We found that if the data of each dichotomy is taken out and expressed in the form of a tree, it is a binary search tree. This is why array binary search is so efficient.

Guess you like

Origin blog.csdn.net/weixin_46862327/article/details/134581069