- Python Tree Data Structure | Tree in Python
- What is a tree in Python?
- Does Python have Tree?
- Introduction to Python Tree
- How Tree is implemented in Python? Tree program in Python
- How to print tree elements | Traverse a Tree in Python
- In-order Traversal
- Pre-order Traversal
- Post-order Traversal
- Using the Insert Method
- Conclusion & Practical Application
- Saved searches
- Use saved searches to filter your results more quickly
- License
- zlargon/print-binary-tree
- Name already in use
- Sign In Required
- Launching GitHub Desktop
- Launching GitHub Desktop
- Launching Xcode
- Launching Visual Studio Code
- Latest commit
- Git stats
- Files
- README.md
- About
- Python Code to Print a Binary Tree
- Step 1: Define the Binary Tree
- Step 2: Insert Data Into the Binary Tree
- Step 4: Python Code to Print a Binary Tree
- Conclusion
- Binarytree: Python Library for Studying Binary Trees
- Requirements
- Installation
- Getting Started
Python Tree Data Structure | Tree in Python
Learn tree in Python- data structure, programs with code examples. Know more about Python tree, how to create it and traverse using pre and post order.
What is a tree in Python?
Trees are non-linear data structures representing nodes connected by edges. Each tree consists of a root or main node known as the Parent node and the left node and right node as Child nodes. It is used for searching and data organization.
Does Python have Tree?
No, Python does not have any trees built-in. On the other hand, you can easily construct by subclassing a Node type from list and writing the traversal methods. We will discuss this later in the article.
Introduction to Python Tree
A binary tree node contains the following components- Data, Left Child, Right Child. The important terms related to a binary tree are:
- Node – The simplest unit of a binary tree.
- Root – It is the topmost element. There is mostly one root in a binary tree.
- Parent – It is the node that is one level upward of the node.
- Child – They are the nodes that are one level downward of the node.
- Leaf – Leaves of a binary tree are the nodes that have no children.
- Level – It is the generation of the node.
For example, a root has level 0, the children of the root node is at level 1 and the grandchildren of the root node is at level 2.
How Tree is implemented in Python? Tree program in Python
To implement and create a tree in Python, we first create a Node class that will represent a single node. The node class will have 3 variables- the left child, the second variable data containing the value for that node and the right child.
class Node: def __init__(self, data): self.left = None self.right = None self.data = data
root = Node(10) root.left = Node(34) root.right = Node(89) root.right.left = Node(45) root.right.right = Node(50)
As a result, the output tree looks like this:
If you create an object of class Node, the __init__ constructor is called, and all the variables inside that constructor will get initialized. The root holds the root node of the tree has a value of 10. We insert the left child with the value 34 and the right child with the value 89. As it is a binary tree, every node can contain a maximum of two nodes. Further, we insert two more nodes to the tree as in 45 and 50. They are the children for node 89.
Note: We can insert any number of nodes we want inside a tree, depending upon the type of tree being created.
How to print tree elements | Traverse a Tree in Python
Since we have created a tree, so we need to traverse the tree to print the tree elements. Traversing means visiting every node in a tree. Every node in a tree is visited three times. There are three types of traversals in a binary tree: in-order traversal, pre-order traversal, and post-order traversal.
In-order Traversal
In this case, we first visit the left child and perform recursion, then we visit the same node for the second time to print that node. It is further followed by the parent node, then followed by recursion on the right child.
The given tree is:
10 / \ 34 89 / \ / \ 20 45 56 54
def inorder(node): if node: inorder(node.left) print(node.data) inorder(node.right)
As a result, the output is:
20 34 45 10 56 89 54
Pre-order Traversal
In this case, while traversing a python tree, we see the root node for the first time and print it. It is then followed by recursion on the left and the right child.
The given tree is:
10 / \ 34 89 / \ / \ 20 45 56 54
def preorder(node): if node: print(node.data) preorder(node.left) preorder(node.right)
As a result, the output is:
10 34 20 45 89 56 54
Post-order Traversal
In this case, while traversing a tree, we do recursion on the left node and the right node. Then we come to the root node to print it.
The given tree is:
10 / \ 34 89 / \ / \ 20 45 56 54
def postorder(node): if node: postorder(node.left) postorder(node.right) print(node.data)
As a result, the output is:
20 45 34 56 54 89 10
Using the Insert Method
To use the insert method in the same node class, we add an insert class to it. This insert class compares the value of the node to the parent node and decides to add it as a left node or a right node. Further, the PrintTree class prints the tree.
Example:
class Node: def __init__(self, data): self.left = None self.right = None self.data = data def insert(self, data): if self.data: if data < self.data: if self.left is None: self.left = Node(data) else: self.left.insert(data) elif data >self.data: if self.right is None: self.right = Node(data) else: self.right.insert(data) else: self.data = data def PrintTree(self): if self.left: self.left.PrintTree() print( self.data), if self.right: self.right.PrintTree() root = Node(30) root.insert(15) root.insert(40) root.insert(35) root.insert(12) root.insert(20) root.PrintTree()
As a result, the output is:
12 15 20 30 35 40
Conclusion & Practical Application
Using trees in Python can be fun, as we saw in the above examples. These are widely used in different software and applications. A strong grip on this topic can be very beneficial for interview purposes and give you an extra edge. After understanding the principles of a tree, practice some problem sets to test your knowledge of trees in python.
Like this article? Follow us on Facebook and LinkedIn.
Saved searches
Use saved searches to filter your results more quickly
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.
Print binary tree in Python
License
zlargon/print-binary-tree
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Name already in use
A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Sign In Required
Please sign in to use Codespaces.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching Xcode
If nothing happens, download Xcode and try again.
Launching Visual Studio Code
Your codespace will open once ready.
There was a problem preparing your codespace, please try again.
Latest commit
Git stats
Files
Failed to load latest commit information.
README.md
Print binary tree in Python
# Create Binary Tree root = TreeNode(0) root.left = TreeNode(1) root.right = TreeNode(2) root.left.left = TreeNode(3) root.left.right = TreeNode(4) root.right.left = TreeNode(5) root.right.right = TreeNode(6) # print tree print_binary_tree(root) # Output: 0 ↙︎ ↘︎ 1 2 ↙︎ ↘︎ ↙︎ ↘︎ 3 4 5 6
Auto calculate the suitable width
# Create Binary Tree root = TreeNode("00000") root.left = TreeNode("00001") root.right = TreeNode("00002") root.left.left = TreeNode("00003") root.left.right = TreeNode("00004") root.right.left = TreeNode("00005") root.right.right = TreeNode("00006") # print tree print_binary_tree(root) # Output: 00000 ↙︎ ↘︎ 00001 00002 ↙︎ ↘︎ ↙︎ ↘︎ 00003 00004 00005 00006
Customize the node width ( node_width )
# Create Binary Tree root = TreeNode("a") root.left = TreeNode("b") root.right = TreeNode("c") root.left.left = TreeNode("d") root.left.right = TreeNode("e") root.right.left = TreeNode("f") root.right.right = TreeNode("g") # print tree print_binary_tree(root, node_width=5) # Output: a ↙︎ ↘︎ b c ↙︎ ↘︎ ↙︎ ↘︎ d e f g
Show the tree level number ( show_level_num )
# Create Binary Tree root = TreeNode("a") root.left = TreeNode("b") root.right = TreeNode("c") root.left.left = TreeNode("d") root.left.right = TreeNode("e") root.right.left = TreeNode("f") root.right.right = TreeNode("g") # print tree print_binary_tree(root, show_level_num=True) # Output: 1: a ↙︎ ↘︎ 2: b c ↙︎ ↘︎ ↙︎ ↘︎ 3: d e f g
About
Print binary tree in Python
Python Code to Print a Binary Tree
A binary tree is a type of data structure in which each node has at most two children, referred to as the left child and the right child. Binary trees are used in various aspects of computer science including sorting and searching. In this tutorial, we will create a binary tree in Python and complete Python code to print a binary tree.
Step 1: Define the Binary Tree
Firstly, we need to create the binary tree structure. Here, we’ll define a simple Node class:
class Node: def __init__(self, data): self.data = data self.left = None self.right = None
This class represents a node in the binary tree, which contains some data and pointers to its left and right children.
Step 2: Insert Data Into the Binary Tree
To insert data into the tree, we’ll define an insert function:
def insert(root, data): if root is None: return Node(data) else: if data
In this function, if the tree is empty (i.e., the root is None), we create a new node with the given data and return it. If the tree is not empty, we recursively insert the data into the left or right subtree depending on its value.
Step 3: Print the Binary Tree
There are several ways you can “print” a binary tree. Here, we’ll implement in-order, pre-order, and post-order traversal methods:
- In-Order Traversal: In this traversal method, the left subtree is visited first, then the root and later the right subtree.
def print_inorder(root): if root: print_inorder(root.left) print(root.data, end=" ") print_inorder(root.right)
- Pre-Order Traversal: In this traversal method, the root node is visited first, then the left subtree and finally the right subtree.
def print_preorder(root): if root: print(root.data, end=" ") print_preorder(root.left) print_preorder(root.right)
- Post-Order Traversal: In this traversal method, the root node is visited last. First, we traverse the left subtree, then the right subtree, and finally the root node.
Step 4: Python Code to Print a Binary Tree
Here is the complete code:
class Node: def __init__(self, data): self.data = data self.left = None self.right = None def insert(root, data): if root is None: return Node(data) else: if data
When you run this code, it will create a binary tree and print the tree using in-order, pre-order, and post-order traversals.
Conclusion
In this Python tutorial, I explained binary tree in Python and Python Code to Print a Binary Tree.
I am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile.
Binarytree: Python Library for Studying Binary Trees
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 binary search trees are also supported. Self-balancing search trees like red-black or AVL will be added in the future.
Check out the documentation for more details.
Binarytree can be used with Graphviz and Jupyter Notebooks as well:
Requirements
Installation
pip install binarytree --upgrade
conda install binarytree -c conda-forge
Getting Started
Binarytree uses the following class to represent a node:
Generate and pretty-print various types of binary trees:
Generate trees with letter values instead of numbers:
Use level-order (breadth-first) indexes to manipulate nodes:
Traverse trees using different algorithms:
Binarytree supports another representation which is more compact but without the indexing properties (this method is often used in Leetcode):
Check out the documentation for more details.