GeezerVisonThe World Wide Web, restored to 800 pixels of glory. | ||||||||||||
| Home|About|Gaming cabinet|Archives|How it works|Starter sites | ||||||||||||
GeezerVison is showing www.w3schools.com — Python Binary Search Trees
❮
❯
Python TutorialPython HOME Python Intro Python Get Started Python Syntax Python Output Python Comments Python Variables
Python Variables
Variable Names
Assign Multiple Values
Output Variables
Global Variables
Variable Exercises
Code Challenge
Python Data Types
Python Numbers
Python Casting
Python Strings
Python Strings
Slicing Strings
Modify Strings
Concatenate Strings
Format Strings
Escape Characters
String Methods
String Exercises
Code Challenge
Python Booleans
Python Operators
Python Operators
Arithmetic Operators
Assignment Operators
Ternary Operator
Comparison Operators
Logical Operators
Identity Operators
Membership Operators
Bitwise Operators
Operator Precedence
Code Challenge
Python Lists
Python Lists
Access List Items
Change List Items
Add List Items
Remove List Items
Loop Lists
List Comprehension
Sort Lists
Copy Lists
Join Lists
List Methods
List Exercises
Code Challenge
Python Tuples
Python Tuples
Access Tuples
Update Tuples
Unpack Tuples
Loop Tuples
Join Tuples
Tuple Methods
Tuple Exercises
Code Challenge
Python Sets
Python Sets
Access Set Items
Add Set Items
Remove Set Items
Loop Sets
Join Sets
Frozenset
Set Methods
Set Exercises
Code Challenge
Python Dictionaries
Python Dictionaries
Access Items
Change Items
Add Items
Remove Items
Loop Dictionaries
Copy Dictionaries
Nested Dictionaries
Dictionary Methods
Dictionary Exercises
Code Challenge
Python If...Else
Python If
Python Elif
Python Else
Shorthand If
Logical Operators
Nested If
Pass Statement
Code Challenge
Python Match
Python While Loops
Python For Loops
Python Functions
Python Functions
Python Arguments
Python *args / **kwargs
Python Scope
Python Decorators
Python Lambda
Python Recursion
Python Generators
Code Challenge
Python Range
Python Arrays
Python Iterators
Python Modules
Python Dates
Python Math
Python JSON
Python RegEx
Python PIP
Python Try...Except
Python String Formatting
Python None
Python User Input
Python VirtualEnv
Python ClassesPython OOP Python Classes/Objects Python __init__ Method Python self Parameter Python Class Properties Python Class Methods Python Magic Methods Python Inheritance Python Polymorphism Python Encapsulation Python Inner ClassesFile HandlingPython File Handling Python Read Files Python Write/Create Files Python Delete FilesPython ModulesNumPy Tutorial Pandas Tutorial SciPy Tutorial Django TutorialPython MatplotlibMatplotlib Intro Matplotlib Get Started Matplotlib Pyplot Matplotlib Plotting Matplotlib Markers Matplotlib Line Matplotlib Labels Matplotlib Grid Matplotlib Subplot Matplotlib Scatter Matplotlib Bars Matplotlib Histograms Matplotlib Pie ChartsMachine LearningGetting Started Mean Median Mode Standard Deviation Percentile Data Distribution Normal Data Distribution Scatter Plot Linear Regression Polynomial Regression Multiple Regression Scale Train/Test Decision Tree Confusion Matrix Hierarchical Clustering Logistic Regression Grid Search Categorical Data K-means Bootstrap Aggregation Cross Validation AUC - ROC Curve K-nearest neighborsPython DSAPython DSA Lists and Arrays Stacks Queues Linked Lists Hash Tables Trees Binary Trees Binary Search Trees AVL Trees Graphs Linear Search Binary Search Bubble Sort Selection Sort Insertion Sort Quick Sort Counting Sort Radix Sort Merge SortPython MySQLMySQL Get Started MySQL Create Database MySQL Create Table MySQL Insert MySQL Select MySQL Where MySQL Order By MySQL Delete MySQL Drop Table MySQL Update MySQL Limit MySQL JoinPython MongoDBMongoDB Get Started MongoDB Create DB MongoDB Collection MongoDB Insert MongoDB Find MongoDB Query MongoDB Sort MongoDB Delete MongoDB Drop Collection MongoDB Update MongoDB LimitPython CertPython CertificatePython How ToRemove List Duplicates Reverse a String Add Two NumbersPython ExamplesPython Examples Python Videos Python Compiler Python Exercises Python Quiz Python Challenges Python Practice Problems Python Server Python Syllabus Python Study Plan Python Interview Q&A Python TrainingPython ReferencePython Overview Python Built-in Functions
abs()
all()
any()
ascii()
bin()
bool()
bytearray()
bytes()
callable()
chr()
compile()
complex()
delattr()
dict()
dir()
divmod()
enumerate()
eval()
exec()
filter()
float()
format()
frozenset()
getattr()
globals()
hasattr()
hex()
id()
input()
int()
isinstance()
issubclass()
iter()
len()
list()
locals()
map()
max()
memoryview()
min()
next()
object()
oct()
open()
ord()
pow()
print()
range()
reversed()
round()
set()
setattr()
slice()
sorted()
str()
sum()
super()
tuple()
type()
vars()
zip()
Python String Methods
capitalize()
casefold()
center()
count()
encode()
endswith()
expandtabs()
find()
format()
format_map()
index()
isalnum()
isalpha()
isascii()
isdecimal()
isdigit()
isidentifier()
islower()
isnumeric()
isprintable()
isspace()
istitle()
isupper()
join()
ljust()
lower()
lstrip()
maketrans()
partition()
replace()
rfind()
rindex()
rjust()
rpartition()
rsplit()
rstrip()
split()
splitlines()
startswith()
strip()
swapcase()
title()
translate()
upper()
zfill()
Python List Methods
Python Dictionary Methods
Python Tuple Methods
Python Set Methods
add()
clear()
copy()
difference()
difference_update()
discard()
intersection()
intersection_update()
isdisjoint()
issubset()
<
issuperset()
>
pop()
remove()
symmetric_difference()
symmetric_difference_update()
union()
update()
Python File Methods
close()
fileno()
flush()
isatty()
read()
readable()
readline()
readlines()
seek()
seekable()
tell()
truncate()
writable()
write()
writelines()
Python Keywords
and
as
assert
async
await
break
case
class
continue
def
del
elif
else
except
False
finally
for
from
global
if
import
in
is
lambda
match
None
nonlocal
not
or
pass
raise
return
True
try
while
with
yield
Python Exceptions
ArithmeticError
AssertionError
AttributeError
Exception
EOFError
FloatingPointError
GeneratorExit
ImportError
IndentationError
IndexError
KeyError
KeyboardInterrupt
LookupError
MemoryError
NameError
NotImplementedError
OSError
OverflowError
ReferenceError
RuntimeError
StopIteration
SyntaxError
TabError
SystemError
SystemExit
TypeError
UnboundLocalError
UnicodeError
UnicodeEncodeError
UnicodeDecodeError
UnicodeTranslateError
ValueError
ZeroDivisionError
Python Glossary
Module ReferenceBuilt-in Modules
abc
aifc
argparse
array
ast
asyncio
atexit
base64
bdb
binascii
bisect
builtins
bz2
calendar
cgi
cgitb
cmd
code
codecs
codeop
collections
colorsys
concurrent
configparser
contextlib
contextvars
copy
copyreg
csv
ctypes
curses
dataclasses
datetime
dbm
decimal
difflib
dis
doctest
email
encodings
ensurepip
enum
errno
faulthandler
filecmp
fileinput
fnmatch
fractions
ftplib
functools
gc
getopt
getpass
gettext
glob
graphlib
gzip
hashlib
heapq
hmac
html
http
idlelib
imaplib
imghdr
imp
importlib
inspect
io
json
keyword
linecache
locale
logging
lzma
mailbox
mailcap
marshal
math
mimetypes
mmap
modulefinder
msilib
msvcrt
multiprocessing
netrc
nntplib
numbers
nis
ntpath
operator
optparse
os
pathlib
pdb
pickle
pickletools
pipes
pkgutil
platform
plistlib
poplib
posix
pprint
profile
pstats
pty
pyclbr
pydoc
py_compile
queue
quopri
random
re
reprlib
resource
rlcompleter
runpy
sched
secrets
select
selectors
shelve
shlex
shutil
signal
site
smtplib
socket
socketserver
sqlite3
ssl
stat
statistics
string
stringprep
struct
subprocess
sunau
symtable
sys
sysconfig
tabnanny
tarfile
telnetlib
tempfile
termios
test
textwrap
threading
time
timeit
tkinter
token
tokenize
tomllib
trace
traceback
tracemalloc
tty
turtle
types
typing
unicodedata
unittest
urllib
uuid
venv
warnings
wave
weakref
webbrowser
wsgiref
xdrlib
xml
xmlrpc
zipapp
zipfile
zipimport
zlib
zoneinfo
Random Module
seed()
getstate()
setstate()
getrandbits()
randrange()
randint()
choice()
choices()
shuffle()
sample()
random()
uniform()
triangular()
Requests Module
Statistics Module
statistics.harmonic_mean()
statistics.mean()
statistics.median()
statistics.median_grouped()
statistics.median_high()
statistics.median_low()
statistics.mode()
statistics.pstdev()
statistics.stdev()
statistics.pvariance()
statistics.variance()
Math Module
math.acos()
math.acosh()
math.asin()
math.asinh()
math.atan()
math.atan2()
math.atanh()
math.ceil()
math.comb()
math.copysign()
math.cos()
math.cosh()
math.degrees()
math.dist()
math.erf()
math.erfc()
math.exp()
math.expm1()
math.fabs()
math.factorial()
math.floor()
math.fmod()
math.frexp()
math.fsum()
math.gamma()
math.gcd()
math.hypot()
math.isclose()
math.isfinite()
math.isinf()
math.isnan()
math.isqrt()
math.ldexp()
math.lgamma()
math.log()
math.log10()
math.log1p()
math.log2()
math.perm()
math.pow()
math.prod()
math.radians()
math.remainder()
math.sin()
math.sinh()
math.sqrt()
math.tan()
math.tanh()
math.trunc()
math.e
math.inf
math.nan
math.pi
math.tau
cMath Module
cmath.acos(x)
cmath.acosh(x)
cmath.asin(x)
cmath.asinh(x)
cmath.atan(x)
cmath.atanh(x)
cmath.cos(x)
cmath.cosh(x)
cmath.exp(x)
cmath.isclose()
cmath.isfinite(x)
cmath.isinf(x)
cmath.isnan(x)
cmath.log(x[, base])
cmath.log10(x)
cmath.phase()
cmath.polar()
cmath.rect()
cmath.sin(x)
cmath.sinh(x)
cmath.sqrt(x)
cmath.tan(x)
cmath.tanh(x)
cmath.e
cmath.inf
cmath.infj
cmath.nan
cmath.nanj
cmath.pi
cmath.tau
Python Binary Search TreesA Binary Search Tree is a Binary Tree where every node's left child has a lower value, and every node's right child has a higher value. A clear advantage with Binary Search Trees is that operations like search, delete, and insert are fast and done without having to shift values in memory.
Share
Binary Search TreesA Binary Search Tree (BST) is a type of Binary Tree data structure, where the following properties must be true for any node "X" in the tree:
These properties makes it faster to search, add and delete values than a regular binary tree. To make this as easy to understand and implement as possible, let's also assume that all values in a Binary Search Tree are unique. The size of a tree is the number of nodes in it A subtree starts with one of the nodes in the tree as a local root, and consists of that node and all its descendants. The descendants of a node are all the child nodes of that node, and all their child nodes, and so on. Just start with a node, and the descendants will be all nodes that are connected below that node. The node's height is the maximum number of edges between that node and a leaf node. A node's in-order successor is the node that comes after it if we were to do in-order traversal. In-order traversal of the BST above would result in node 13 coming before node 14, and so the successor of node 13 is node 14. Traversal of a Binary Search TreeJust to confirm that we actually have a Binary Search Tree data structure in front of us, we can check if the properties at the top of this page are true. So for every node in the figure above, check if all the values to the left of the node are lower, and that all values to the right are higher. Another way to check if a Binary Tree is BST, is to do an in-order traversal (like we did on the previous page) and check if the resulting list of values are in an increasing order. The code below is an implementation of the Binary Search Tree in the figure above, with traversal. ExampleTraversal of a Binary Search Tree in Python
class TreeNode:
Try it Yourself »
def __init__(self, data): self.data = data self.left = None self.right = None def inOrderTraversal(node): if node is None: return inOrderTraversal(node.left) print(node.data, end=", ") inOrderTraversal(node.right) root = TreeNode(13) node7 = TreeNode(7) node15 = TreeNode(15) node3 = TreeNode(3) node8 = TreeNode(8) node14 = TreeNode(14) node19 = TreeNode(19) node18 = TreeNode(18) root.left = node7 root.right = node15 node7.left = node3 node7.right = node8 node15.left = node14 node15.right = node19 node19.left = node18 # Traverse inOrderTraversal(root) As we can see by running the code example above, the in-order traversal produces a list of numbers in an increasing (ascending) order, which means that this Binary Tree is a Binary Search Tree. Search for a Value in a BSTSearching for a value in a BST is very similar to how we found a value using Binary Search on an array. For Binary Search to work, the array must be sorted already, and searching for a value in an array can then be done really fast. Similarly, searching for a value in a BST can also be done really fast because of how the nodes are placed. How it works:
The algorithm can be implemented like this: ExampleSearch the Tree for the value "13"
def search(node, target):
Try it Yourself »
if node is None: return None elif node.data == target: return node elif target < node.data: return search(node.left, target) else: return search(node.right, target) # Search for a value result = search(root, 13) if result: print(f"Found the node with value: {result.data}") else: print("Value not found in the BST.") The time complexity for searching a BST for a value is For a BST with most nodes on the right side for example, the height of the tree becomes larger than it needs to be, and the worst case search will take longer. Such trees are called unbalanced. Both Binary Search Trees above have the same nodes, and in-order traversal of both trees gives us the same result but the height is very different. It takes longer time to search the unbalanced tree above because it is higher. We will use the next page to describe a type of Binary Tree called AVL Trees. AVL trees are self-balancing, which means that the height of the tree is kept to a minimum so that operations like search, insertion and deletion take less time. Insert a Node in a BSTInserting a node in a BST is similar to searching for a value. How it works:
Inserting nodes as described above means that an inserted node will always become a new leaf node. All nodes in the BST are unique, so in case we find the same value as the one we want to insert, we do nothing. This is how node insertion in BST can be implemented: ExampleInserting a node in a BST:
def insert(node, data):
Try it Yourself »
if node is None: return TreeNode(data) else: if data < node.data: node.left = insert(node.left, data) elif data > node.data: node.right = insert(node.right, data) return node # Inserting new value into the BST insert(root, 10) Find The Lowest Value in a BST SubtreeThe next section will explain how we can delete a node in a BST, but to do that we need a function that finds the lowest value in a node's subtree. How it works:
This is how a function for finding the lowest value in the subtree of a BST node looks like: ExampleFind the lowest value in a BST subtree
def minValueNode(node):
Try it Yourself »
current = node while current.left is not None: current = current.left return current # Find Lowest print("\nLowest value:",minValueNode(root).data) We will use this Delete a Node in a BSTTo delete a node, our function must first search the BST to find it. After the node is found there are three different cases where deleting a node must be done differently. How it works:
In step 3 above, the successor we find will always be a leaf node, and because it is the node that comes right after the node we want to delete, we can swap values with it and delete it. This is how a BST can be implemented with functionality for deleting a node: ExampleDelete a Node in a BST
def delete(node, data):
Try it Yourself »
if not node: return None if data < node.data: node.left = delete(node.left, data) elif data > node.data: node.right = delete(node.right, data) else: # Node with only one child or no child if not node.left: temp = node.right node = None return temp elif not node.right: temp = node.left node = None return temp # Node with two children, get the in-order successor node.data = minValueNode(node.right).data node.right = delete(node.right, node.data) return node # Delete node 15 delete(root,15) Line 1: The Line 2-8: This is searching for the node with correct Line 9-22: The node we want to delete has been found. There are three such cases:
Line 24: BST Compared to Other Data StructuresBinary Search Trees take the best from two other data structures: Arrays and Linked Lists.
Searching a BST is just as fast as Binary Search on an array, with the same time complexity And deleting and inserting new values can be done without shifting elements in memory, just like with Linked Lists. BST Balance and Time ComplexityOn a Binary Search Tree, operations like inserting a new node, deleting a node, or searching for a node are actually The reason why we wrote that searching for a value is We call this tree balanced because there are approximately the same number of nodes on the left and right side of the tree. The exact way to tell that a Binary Tree is balanced is that the height of the left and right subtrees of any node only differs by one.
In the image above, the left subtree of the root node has height For a balanced BST, with a large number of nodes (big But, in case the BST is completely unbalanced, like in the image below, the height of the tree is approximately the same as the number of nodes,
So, to optimize operations on a BST, the height must be minimized, and to do that the tree must be balanced. And keeping a Binary Search Tree balanced is exactly what AVL Trees do, which is the data structure explained on the next page. Free account Track your progress
XP earned 0
Day streak 0
Spaces 0
League —
New Learn in Adventure Mode W3Schools Adventure AppCoding fundamentals as bite-sized lessons and challenges.
×
Contact SalesIf you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail: Report ErrorIf you want to report an error, or if you want to make a suggestion, send us an e-mail: Top TutorialsHTML TutorialCSS Tutorial JavaScript Tutorial How To Tutorial SQL Tutorial Python Tutorial W3.CSS Tutorial Bootstrap Tutorial PHP Tutorial Java Tutorial C++ Tutorial jQuery Tutorial Top ReferencesHTML ReferenceCSS Reference JavaScript Reference SQL Reference Python Reference W3.CSS Reference Bootstrap Reference PHP Reference HTML Colors Java Reference AngularJS Reference jQuery Reference
W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning.
Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookies and privacy policy. Copyright 1999-2026 by Refsnes Data. All Rights Reserved. W3Schools is Powered by W3.CSS. | ||||||||||||
| You are visitor 01402503 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |