GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Tutorials
  • My W3Schools
  • W3Schools app iOS & Android NEW
  • Spaces
  • Get Certified
  • Plus
  • Practice
  • Campus (previously Academy)
  • Logout
  • 
  • 
  • 
  • 
  • Sign in

This view

  • Original page
  • New address

GeezerVison is showing www.w3schools.com — Python Binary Trees

Menu
Search field
×
See More  
NEW W3Schools app iOS & Android Start the adventure
Sign In
★ +1 Spaces Upgrade Paid Courses Spaces Upgrade Paid Courses
   ❮     
     ❯   
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP C C++ C# AWS W3.CSS HOW TO BOOTSTRAP REACT MYSQL JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS DSA TYPESCRIPT ANGULAR ANGULARJS GIT POSTGRESQL MONGODB ASP AI R GO KOTLIN SWIFT SASS VUE GEN AI SCIPY CYBERSECURITY DATA SCIENCE INTRO TO PROGRAMMING INTRO TO HTML & CSS BASH RUST TOOLS

Python Tutorial

Python HOME Python Intro Python Get Started Python Syntax
Syntax Statements Code Challenge
Python Output
Print Text Print Numbers Code Challenge
Python Comments
Comments Code Challenge
Python Variables
Python Variables Variable Names Assign Multiple Values Output Variables Global Variables Variable Exercises Code Challenge
Python Data Types
Data Types Code Challenge
Python Numbers
Numbers Code Challenge
Python Casting
Casting Code Challenge
Python Strings
Python Strings Slicing Strings Modify Strings Concatenate Strings Format Strings Escape Characters String Methods String Exercises Code Challenge
Python Booleans
Booleans Code Challenge
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
Match Code Challenge
Python While Loops
While Loops Code Challenge
Python For Loops
For Loops Code Challenge
Python Functions
Python Functions Python Arguments Python *args / **kwargs Python Scope Python Decorators Python Lambda Python Recursion Python Generators Code Challenge
Python Range
Range Code Challenge
Python Arrays
Arrays Code Challenge
Python Iterators
Iterators Code Challenge
Python Modules
Modules Code Challenge
Python Dates
Dates Code Challenge
Python Math
Math Code Challenge
Python JSON
JSON Code Challenge
Python RegEx
RegEx Code Challenge
Python PIP Python Try...Except
Try...Except Code Challenge
Python String Formatting
String Formatting Code Challenge
Python None
None Code Challenge
Python User Input Python VirtualEnv

Python Classes

Python OOP Python Classes/Objects
Classes/Objects Code Challenge
Python __init__ Method
__init__ Method Code Challenge
Python self Parameter
self Parameter Code Challenge
Python Class Properties
Class Properties Code Challenge
Python Class Methods
Class Methods Code Challenge
Python Magic Methods
Magic Methods __str__ __repr__ __eq__ __add__ __len__ __lt__ __contains__ __call__ Code Challenge
Python Inheritance
Inheritance Code Challenge
Python Polymorphism
Polymorphism Code Challenge
Python Encapsulation
Encapsulation Code Challenge
Python Inner Classes

File Handling

Python File Handling Python Read Files Python Write/Create Files Python Delete Files

Python Modules

NumPy Tutorial Pandas Tutorial SciPy Tutorial Django Tutorial

Python Matplotlib

Matplotlib 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 Charts

Machine Learning

Getting 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 neighbors

Python DSA

Python 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 Sort

Python MySQL

MySQL 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 Join

Python MongoDB

MongoDB Get Started MongoDB Create DB MongoDB Collection MongoDB Insert MongoDB Find MongoDB Query MongoDB Sort MongoDB Delete MongoDB Drop Collection MongoDB Update MongoDB Limit

Python Cert

Python Certificate

Python How To

Remove List Duplicates Reverse a String Add Two Numbers

Python Examples

Python 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 Training

Python Reference

Python 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
append() clear() copy() count() extend() index() insert() pop() remove() reverse() sort()
Python Dictionary Methods
clear() copy() fromkeys() get() items() keys() pop() popitem() setdefault() update() values()
Python Tuple Methods
count() index()
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 Reference

Built-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
delete(url, args) get(url, params, args) head(url, args) post(url, data, json, args)
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 Trees

❮ Previous Next ❯

A tree is a hierarchical data structure consisting of nodes connected by edges.

Each node contains a value and references to its child nodes.


Share

Binary Trees

A Binary Tree is a type of tree data structure where each node can have a maximum of two child nodes, a left child node and a right child node.

This restriction, that a node can have a maximum of two child nodes, gives us many benefits:

  • Algorithms like traversing, searching, insertion and deletion become easier to understand, to implement, and run faster.
  • Keeping data sorted in a Binary Search Tree (BST) makes searching very efficient.
  • Balancing trees is easier to do with a limited number of child nodes, using an AVL Binary Tree for example.
  • Binary Trees can be represented as arrays, making the tree more memory efficient.

Binary Tree Implementation

The Binary Tree above can be implemented much like a Linked List, except that instead of linking each node to one next node, we create a structure where each node can be linked to both its left and right child nodes.

Example

Create a Binary Tree in Python:

class TreeNode:
  def __init__(self, data):
    self.data = data
    self.left = None
    self.right = None

root = TreeNode('R')
nodeA = TreeNode('A')
nodeB = TreeNode('B')
nodeC = TreeNode('C')
nodeD = TreeNode('D')
nodeE = TreeNode('E')
nodeF = TreeNode('F')
nodeG = TreeNode('G')

root.left = nodeA
root.right = nodeB

nodeA.left = nodeC
nodeA.right = nodeD

nodeB.left = nodeE
nodeB.right = nodeF

nodeF.left = nodeG

# Test
print("root.right.left.data:", root.right.left.data)
Try it Yourself »


Types of Binary Trees

There are different variants, or types, of Binary Trees worth discussing to get a better understanding of how Binary Trees can be structured.

The different kinds of Binary Trees are also worth mentioning now as these words and concepts will be used later in the tutorial.

Below are short explanations of different types of Binary Tree structures, and below the explanations are drawings of these kinds of structures to make it as easy to understand as possible.

A balanced Binary Tree has at most 1 in difference between its left and right subtree heights, for each node in the tree.

A complete Binary Tree has all levels full of nodes, except the last level, which is can also be full, or filled from left to right. The properties of a complete Binary Tree means it is also balanced.

A full Binary Tree is a kind of tree where each node has either 0 or 2 child nodes.

A perfect Binary Tree has all leaf nodes on the same level, which means that all levels are full of nodes, and all internal nodes have two child nodes.The properties of a perfect Binary Tree means it is also full, balanced, and complete.

Balanced
Complete and balanced
Full
Perfect, full, balanced and complete

Binary Tree Traversal

Going through a Tree by visiting every node, one node at a time, is called traversal.

Since Arrays and Linked Lists are linear data structures, there is only one obvious way to traverse these: start at the first element, or node, and continue to visit the next until you have visited them all.

But since a Tree can branch out in different directions (non-linear), there are different ways of traversing Trees.

There are two main categories of Tree traversal methods:

Breadth First Search (BFS) is when the nodes on the same level are visited before going to the next level in the tree. This means that the tree is explored in a more sideways direction.

Depth First Search (DFS) is when the traversal moves down the tree all the way to the leaf nodes, exploring the tree branch by branch in a downwards direction.

There are three different types of DFS traversals:

  • pre-order
  • in-order
  • post-order

Pre-order Traversal of Binary Trees

Pre-order Traversal is a type of Depth First Search, where each node is visited in a certain order..

Pre-order Traversal is done by visiting the root node first, then recursively do a pre-order traversal of the left subtree, followed by a recursive pre-order traversal of the right subtree. It's used for creating a copy of the tree, prefix notation of an expression tree, etc.

This traversal is "pre" order because the node is visited "before" the recursive pre-order traversal of the left and right subtrees.

This is how the code for pre-order traversal looks like:

Example

A pre-order traversal:

def preOrderTraversal(node):
  if node is None:
    return
  print(node.data, end=", ")
  preOrderTraversal(node.left)
  preOrderTraversal(node.right)
Try it Yourself »

The first node to be printed is node R, as the Pre-order Traversal works by first visiting, or printing, the current node (line 4), before calling the left and right child nodes recursively (line 5 and 6).

The preOrderTraversal() function keeps traversing the left subtree recursively (line 5), before going on to traversing the right subtree (line 6). So the next nodes that are printed are 'A' and then 'C'.

The first time the argument node is None is when the left child of node C is given as an argument (C has no left child).

After None is returned the first time when calling C's left child, C's right child also returns None, and then the recursive calls continue to propagate back so that A's right child D is the next to be printed.

The code continues to propagate back so that the rest of the nodes in R's right subtree gets printed.


In-order Traversal of Binary Trees

In-order Traversal is a type of Depth First Search, where each node is visited in a certain order.

In-order Traversal does a recursive In-order Traversal of the left subtree, visits the root node, and finally, does a recursive In-order Traversal of the right subtree. This traversal is mainly used for Binary Search Trees where it returns values in ascending order.

What makes this traversal "in" order, is that the node is visited in between the recursive function calls. The node is visited after the In-order Traversal of the left subtree, and before the In-order Traversal of the right subtree.

This is how the code for In-order Traversal looks like:

Example

Create an In-order Traversal:

def inOrderTraversal(node):
  if node is None:
    return
  inOrderTraversal(node.left)
  print(node.data, end=", ")
  inOrderTraversal(node.right)
Try it Yourself »

The inOrderTraversal() function keeps calling itself with the current left child node as an argument (line 4) until that argument is None and the function returns (line 2-3).

The first time the argument node is None is when the left child of node C is given as an argument (C has no left child).

After that, the data part of node C is printed (line 5), which means that 'C' is the first thing that gets printed.

Then, node C's right child is given as an argument (line 6), which is None, so the function call returns without doing anything else.

After 'C' is printed, the previous inOrderTraversal() function calls continue to run, so that 'A' gets printed, then 'D', then 'R', and so on.


Post-order Traversal of Binary Trees

Post-order Traversal is a type of Depth First Search, where each node is visited in a certain order..

Post-order Traversal works by recursively doing a Post-order Traversal of the left subtree and the right subtree, followed by a visit to the root node. It is used for deleting a tree, post-fix notation of an expression tree, etc.

What makes this traversal "post" is that visiting a node is done "after" the left and right child nodes are called recursively.

This is how the code for Post-order Traversal looks like:

Example

Post-order Traversal:

def postOrderTraversal(node):
  if node is None:
    return
  postOrderTraversal(node.left)
  postOrderTraversal(node.right)
  print(node.data, end=", ")
Try it Yourself »

The postOrderTraversal() function keeps traversing the left subtree recursively (line 4), until None is returned when C's left child node is called as the node argument.

After C's left child node returns None, line 5 runs and C's right child node returns None, and then the letter 'C' is printed (line 6).

This means that C is visited, or printed, "after" its left and right child nodes are traversed, that is why it is called "post" order traversal.

The postOrderTraversal() function continues to propagate back to previous recursive function calls, so the next node to be printed is 'D', then 'A'.

The function continues to propagate back and printing nodes until all nodes are printed, or visited.

❮ Previous Next ❯
★ +1
Sign in to track progress
W3Schools Full Access - your next career move

REMOVE ADS

This way to the W3Schools Adventure app
Learn more about Adventure Mode›

Free account

Track your progress

XP earned 0 Day streak 0 Spaces 0 League —
Sign in to track progress

New

Learn in Adventure Mode W3Schools Adventure App

Coding fundamentals as bite-sized lessons and challenges.

PLUS
SPACES
GET CERTIFIED
FOR TEACHERS
PRACTICE
CONTACT US
×

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
[email protected]

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
[email protected]

Top Tutorials
HTML Tutorial
CSS Tutorial
JavaScript Tutorial
How To Tutorial
SQL Tutorial
Python Tutorial
W3.CSS Tutorial
Bootstrap Tutorial
PHP Tutorial
Java Tutorial
C++ Tutorial
jQuery Tutorial
Top References
HTML Reference
CSS Reference
JavaScript Reference
SQL Reference
Python Reference
W3.CSS Reference
Bootstrap Reference
PHP Reference
HTML Colors
Java Reference
AngularJS Reference
jQuery Reference
Top Examples
HTML Examples
CSS Examples
JavaScript Examples
How To Examples
SQL Examples
Python Examples
W3.CSS Examples
Bootstrap Examples
PHP Examples
Java Examples
XML Examples
jQuery Examples
Get Certified
HTML Certificate
CSS Certificate
JavaScript Certificate
Front End Certificate
SQL Certificate
Python Certificate
PHP Certificate
jQuery Certificate
Java Certificate
C++ Certificate
C# Certificate
XML Certificate
   
FORUM ABOUT CAMPUS
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.