- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Program to invert a binary tree in Python
Suppose we have a binary tree root, we have to invert it so that its left subtree and right subtree are exchanged and their children are also exchanged recursively.
So, if the input is like
then the output will be
To solve this, we will follow these steps −
Define a method solve(), this will take node
if root is null, then
return
left of root := solve(right of root)
right of root := solve(right of root)
return root
Let us see the following implementation to get better understanding −
Example
class TreeNode: def __init__(self, value): self.val = value self.left = None self.right = None def inorder(root): if root: inorder(root.left) print(root.val, end=', ') inorder(root.right) class Solution: def solve(self, root): if not root: return root.left, root.right = self.solve(root.right), self.solve(root.left) return root ob = Solution() root = TreeNode(5) root.left = TreeNode(4) root.right = TreeNode(10) root.right.left = TreeNode(7) root.right.right = TreeNode(15) inv = ob.solve(root) inorder(inv)
Input
root = TreeNode(5) root.left = TreeNode(4) root.right = TreeNode(10) root.right.left = TreeNode(7) root.right.right = TreeNode(15)
Output
15, 10, 7, 5, 4,
- Related Articles
- Invert Binary Tree in Python
- How to invert a binary search tree using recursion in C#?
- Python Program to Sort using a Binary Search Tree
- Program to fix a erroneous binary tree using Python
- Program to find top view of a binary tree in Python
- Program to find second deepest node in a binary tree in python
- Program to find the maximum width of a binary tree in Python
- Program to find k-length paths on a binary tree in Python
- Program to perform an Inorder Traversal of a binary tree in Python
- Program to find sibling value of a binary tree node in Python
- Program to change the root of a binary tree using Python
- Python Program to Implement Binary Tree using Linked List
- Program to create linked list to binary search tree in Python
- Program to find number of only child in a binary tree in python
- Golang program to define a binary tree

Advertisements