All Projects → joowani → Binarytree

joowani / Binarytree

Licence: mit
Python Library for Studying Binary Trees

Programming Languages

python
139335 projects - #7 most used programming language

Projects that are alternatives of or similar to Binarytree

Algorithms
Solved algorithms and data structures problems in many languages
Stars: ✭ 1,021 (-39.73%)
Mutual labels:  algorithm, data-structures, heap, interview, interview-practice
Interactive Coding Challenges
120+ interactive Python coding interview challenges (algorithms and data structures). Includes Anki flashcards.
Stars: ✭ 24,317 (+1335.48%)
Mutual labels:  algorithm, data-structure, interview, interview-practice
Algorithms And Data Structures In Java
Algorithms and Data Structures in Java
Stars: ✭ 498 (-70.6%)
Mutual labels:  algorithm, data-structures, interview, interview-practice
Interview
📚 C/C++ 技术面试基础知识总结,包括语言、程序库、数据结构、算法、系统、网络、链接装载库等知识及面试经验、招聘、内推等信息。This repository is a summary of the basic knowledge of recruiting job seekers and beginners in the direction of C/C++ technology, including language, program library, data structure, algorithm, system, network, link loading library, interview experience, recruitment, recommendatio…
Stars: ✭ 21,608 (+1175.56%)
Mutual labels:  algorithm, data-structures, interview, interview-practice
Interview Questions
List of all the Interview questions practiced from online resources and books
Stars: ✭ 187 (-88.96%)
Mutual labels:  algorithm, data-structures, interview, interview-practice
Algodeck
An Open-Source Collection of 200+ Algorithmic Flash Cards to Help you Preparing your Algorithm & Data Structure Interview 💯
Stars: ✭ 4,441 (+162.16%)
Mutual labels:  algorithm, data-structures, heap, interview-practice
Leetcode Sol Res
Clean, Understandable Solutions and Resources for LeetCode Online Judge Algorithm Problems.
Stars: ✭ 1,647 (-2.77%)
Mutual labels:  algorithm, interview, interview-practice
Lintcode
📘 C++11 Solutions of All 289 LintCode Problems (No More Updates)
Stars: ✭ 570 (-66.35%)
Mutual labels:  algorithm, data-structure, interview-practice
Book on python algorithms and data structure
🪐 Book on Python, Algorithms, and Data Structures. 🪐
Stars: ✭ 604 (-64.34%)
Mutual labels:  algorithm, data-structure, interview
Oh My Python
剑指offer(python版)/ 算法图解 / python基础 / 数据结构
Stars: ✭ 119 (-92.98%)
Mutual labels:  algorithm, data-structures, interview-practice
C Sharp Algorithms
📚 📈 Plug-and-play class-library project of standard Data Structures and Algorithms in C#
Stars: ✭ 4,684 (+176.51%)
Mutual labels:  data-structures, binary-trees, heaps
Dsa.js Data Structures Algorithms Javascript
🥞Data Structures and Algorithms explained and implemented in JavaScript + eBook
Stars: ✭ 6,251 (+269.01%)
Mutual labels:  algorithm, data-structures, heap
Algorithm
Algorithm is a library of tools that is used to create intelligent applications.
Stars: ✭ 787 (-53.54%)
Mutual labels:  algorithm, data-structures, data-structure
Algorithms and data structures
180+ Algorithm & Data Structure Problems using C++
Stars: ✭ 4,667 (+175.5%)
Mutual labels:  algorithm, data-structures, interview-practice
Sde Interview Questions
Most comprehensive list 📋 of tech interview questions 📘 of companies scraped from Geeksforgeeks, CareerCup and Glassdoor.
Stars: ✭ 5,406 (+219.13%)
Mutual labels:  algorithm, data-structures, interview-practice
Tech Refrigerator
🍰 기술 냉장고입니다. 🛒 기술 면접 , 전공 시험 , 지식 함양 등 분명 도움될 거예요! 🤟
Stars: ✭ 699 (-58.74%)
Mutual labels:  algorithm, data-structures, interview
Apachecn Algo Zh
ApacheCN 数据结构与算法译文集
Stars: ✭ 10,498 (+519.72%)
Mutual labels:  algorithm, data-structure, interview
Data Structure And Algorithms
A complete and efficient guide for Data Structure and Algorithms.
Stars: ✭ 48 (-97.17%)
Mutual labels:  algorithm, data-structures, data-structure
Algorithms
📝 算法导论与JavaScript实现
Stars: ✭ 126 (-92.56%)
Mutual labels:  algorithm, data-structures, interview
Leetcode Swift
Solutions to LeetCode by Swift
Stars: ✭ 4,099 (+141.97%)
Mutual labels:  algorithm, data-structures, interview

Binarytree: Python Library for Studying Binary Trees

Build CodeQL codecov PyPI version GitHub license Python version

Are you studying binary trees for your next exam, assignment or technical interview?

Binarytree is a Python library which lets you generate, visualize, inspect and manipulate binary trees. Skip the tedious work of setting up test data, and dive straight into practising your algorithms. Heaps and BSTs (binary search trees) are also supported.

IPython Demo

Binarytree can be used with Graphviz and Jupyter Notebooks as well:

Jupyter Demo

Requirements

Python 3.6+

Installation

Install via pip:

pip install binarytree

For conda users:

conda install binarytree -c conda-forge

Getting Started

Binarytree uses the following class to represent a node:

class Node:

    def __init__(self, value, left=None, right=None):
        self.value = value  # The node value (integer)
        self.left = left    # Left child
        self.right = right  # Right child

Generate and pretty-print various types of binary trees:

from binarytree import tree, bst, heap

# Generate a random binary tree and return its root node.
my_tree = tree(height=3, is_perfect=False)

# Generate a random BST and return its root node.
my_bst = bst(height=3, is_perfect=True)

# Generate a random max heap and return its root node.
my_heap = heap(height=3, is_max=True, is_perfect=False)

# Pretty-print the trees in stdout.
print(my_tree)
#
#        _______1_____
#       /             \
#      4__          ___3
#     /   \        /    \
#    0     9      13     14
#         / \       \
#        7   10      2
#
print(my_bst)
#
#            ______7_______
#           /              \
#        __3__           ___11___
#       /     \         /        \
#      1       5       9         _13
#     / \     / \     / \       /   \
#    0   2   4   6   8   10    12    14
#
print(my_heap)
#
#              _____14__
#             /         \
#        ____13__        9
#       /        \      / \
#      12         7    3   8
#     /  \       /
#    0    10    6
#

Build your own trees:

from binarytree import Node

root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.right = Node(4)

print(root)
#
#      __1
#     /   \
#    2     3
#     \
#      4
#

Inspect tree properties:

from binarytree import Node

root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)

print(root)
#
#        __1
#       /   \
#      2     3
#     / \
#    4   5
#
assert root.height == 2
assert root.is_balanced is True
assert root.is_bst is False
assert root.is_complete is True
assert root.is_max_heap is False
assert root.is_min_heap is True
assert root.is_perfect is False
assert root.is_strict is True
assert root.leaf_count == 3
assert root.max_leaf_depth == 2
assert root.max_node_value == 5
assert root.min_leaf_depth == 1
assert root.min_node_value == 1
assert root.size == 5

# See all properties at once.
assert root.properties == {
    'height': 2,
    'is_balanced': True,
    'is_bst': False,
    'is_complete': True,
    'is_max_heap': False,
    'is_min_heap': True,
    'is_perfect': False,
    'is_strict': True,
    'leaf_count': 3,
    'max_leaf_depth': 2,
    'max_node_value': 5,
    'min_leaf_depth': 1,
    'min_node_value': 1,
    'size': 5
}

print(root.leaves)
# [Node(3), Node(4), Node(5)]

print(root.levels)
# [[Node(1)], [Node(2), Node(3)], [Node(4), Node(5)]]

Compare and clone trees:

from binarytree import tree

original = tree()

# Clone the binary tree.
clone = original.clone()

# Check if the trees are equal.
original.equals(clone)

Use level-order (breadth-first) indexes to manipulate nodes:

from binarytree import Node

root = Node(1)                  # index: 0, value: 1
root.left = Node(2)             # index: 1, value: 2
root.right = Node(3)            # index: 2, value: 3
root.left.right = Node(4)       # index: 4, value: 4
root.left.right.left = Node(5)  # index: 9, value: 5

print(root)
#
#      ____1
#     /     \
#    2__     3
#       \
#        4
#       /
#      5
#
root.pprint(index=True)
#
#       _________0-1_
#      /             \
#    1-2_____        2-3
#            \
#           _4-4
#          /
#        9-5
#
print(root[9])
# Node(5)

# Replace the node/subtree at index 4.
root[4] = Node(6, left=Node(7), right=Node(8))
root.pprint(index=True)
#
#       ______________0-1_
#      /                  \
#    1-2_____             2-3
#            \
#           _4-6_
#          /     \
#        9-7     10-8
#

# Delete the node/subtree at index 1.
del root[1]
root.pprint(index=True)
#
#    0-1_
#        \
#        2-3

Traverse trees using different algorithms:

from binarytree import Node

root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)

print(root)
#
#        __1
#       /   \
#      2     3
#     / \
#    4   5
#
print(root.inorder)
# [Node(4), Node(2), Node(5), Node(1), Node(3)]

print(root.preorder)
# [Node(1), Node(2), Node(4), Node(5), Node(3)]

print(root.postorder) 
# [Node(4), Node(5), Node(2), Node(3), Node(1)]

print(root.levelorder) 
# [Node(1), Node(2), Node(3), Node(4), Node(5)]

print(list(root)) # Equivalent to root.levelorder
# [Node(1), Node(2), Node(3), Node(4), Node(5)]

Convert to list representations:

from binarytree import build

# Build a tree from list representation
values = [7, 3, 2, 6, 9, None, 1, 5, 8]
root = build(values)
print(root)
#
#            __7
#           /   \
#        __3     2
#       /   \     \
#      6     9     1
#     / \
#    5   8
#

# Go back to list representation
print(root.values) 
# [7, 3, 2, 6, 9, None, 1, 5, 8]

Binarytree supports another representation which is more compact but without the indexing properties:

from binarytree import build, build2, Node

# First let's create an example tree.
root = Node(1)
root.left = Node(2)
root.left.left = Node(3)
root.left.left.left = Node(4)
root.left.left.right = Node(5)
print(root)
#
#           1
#          /
#       __2
#      /
#     3
#    / \
#   4   5

# First representation is was already shown above.
# All "null" nodes in each level are present.
print(root.values)
# [1, 2, None, 3, None, None, None, 4, 5]

# Second representation is more compact but without the indexing properties.
print(root.values2)
# [1, 2, None, 3, None, 4, 5]

# Build trees from the list representations
tree1 = build(root.values)
tree2 = build2(root.values2)
assert tree1.equals(tree2) is True

Check out the documentation for more details.

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].