[JS data structure and algorithm] Binary search tree

table of Contents

1. What is a binary search tree

Second, the advantages of binary search tree


1. What is a binary search tree

Binary Search Tree (BST, Binary Search Tree), also known as Binary Sort Tree or Binary Search Tree.

The binary search tree is a binary tree, and it can also be empty.

If the binary search tree is not empty, then the following conditions are met:

  • All the key values ​​of the non-empty left subtree are less than the key value of its root node.
  • All the key values ​​of the non-empty right subtree are greater than the key value of its root node.
  • The left and right subtrees themselves are also binary search trees.

Second, the advantages of binary search tree

Suppose that in Figure a, we want to find the node 24. First, we start from the root 18. We find that 24 is greater than 18. According to the characteristics of the binary search tree: all the key values ​​of the non-empty right subtree are greater than its root. The key value of the node. So we directly exclude all the elements on the left, go directly into the right subtree, and compare 30 to find that 24 is smaller than 30, so the left subtree of 30 is 24.

Then let's get to know the idea of ​​dichotomy.

Binary search method, also known as halving, for an ordered array.

(1) First, start the search from the middle element of the array. If the element is the target element, the search ends, otherwise the next step is executed.

(2) If the target element is larger/smaller than the middle element, search in the half of the array that is larger/smaller than the middle element, and then repeat the operation of step (1).

(3) If a step array is empty, it means that the target element cannot be found.

Similarly, the binary search tree is the idea of ​​binary search, and the time complexity can be reduced to O(logn)

 

Summary: Binary search tree is to standardize the structure of a tree and the storage of data when inserting, which facilitates the subsequent search and modification operations, and greatly improves the efficiency.

Three, the disadvantages of binary search tree

  • The delete operation is not only to delete a node, but also to consider the value of the node
  • When storing an ordered linear table, it will cause a waste of space.
  • For a group of large amounts of data, there is a partial ordering situation, which will make a tree become one-sided, that is, an unbalanced situation will occur. (This has a balanced tree)

Guess you like

Origin blog.csdn.net/weixin_42339197/article/details/99689919