Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Binary Search Tree

Binary Search Tree

I. Concept and Introduction

A binary search tree (English: Binary Search Tree), also called a binary lookup tree, ordered binary tree, or sorted binary tree, satisfies the following conditions:

Its left and right subtrees are also binary search trees.

As shown in the figure below:

II. Applicability Notes

A binary search tree has efficient insertion, deletion, and query operations.

The average time complexity is O(log n), and the worst case is O(n). Unlike a heap, a binary search tree is not necessarily a complete binary tree, and its underlying structure is not easily represented directly by an array, so a linked list is used to implement the binary search tree.

  Find elements Insert elements Delete elements
Ordinary Array O(n) O(n) O(n)
Sorted Array O(logn) O(n) O(n)
Binary Search Tree O(logn) O(logn) O(logn)

Below we first introduce the array-based binary search method as a source of ideas, and then continue to introduce the search method of binary search trees.

III. Diagram of the Binary Search Process

The idea of binary search was proposed in 1946. The search problem is a very important fundamental problem in computer science, and binary search can only be used on ordered sequences. If we want to find an element, we first look at the relationship between the middle value V of the array and the data to be searched, in three cases:

IV. Java Example Code

Source code package download:Download

src/runoob/binary/BinarySearch.java file code:

package

runoob.binarySearch

;

/**
 * Binary Search
 */

public

class

BinarySearch

{

   

// Binary search: find target in the sorted array arr

   

// If target is found, return the corresponding index

   

// If target is not found, return -1

   

public

static

int

find

(

Comparable

[

]

arr,

Comparable

target

)

{

       

// Find target within arr[l...r]

       

int

l

=

0

, r

=

arr.

length

1

;

       

while

(

l

<=

r

)

{

           

//int mid = (l + r)/2;

           

// To prevent integer overflow in extreme cases, use the following logic to compute mid

           

int

mid

=

l

(

r

l

)

/

2

;

           

if

(

arr

[

mid

]

.

compareTo

(

target

)

==

0

)

               

return

mid

;

           

if

(

arr

[

mid

]

.

compareTo

(

target

)

0

)

                r

=

mid

1

;

           

else

                l

=

mid

1

;

       

}

       

return

1

;

   

}

}