'Inverting binary tree (recursive)
I can't figure out how to output a reversed binary tree. This is what I've come up so far + my pseudo code.
Creating a binary tree
#Creating the binary tree
from binarytree import build
from binarytree import tree
# List of nodes
nodes =[4, 2, 7, 1, 3, 6, 9]
# Builidng the binary tree
binary_tree = build(nodes)
print('Binary tree from example :\n ',
binary_tree)
# Getting list of nodes from
# binarytree
print('\nList from binary tree :',
binary_tree.values)
Output:
Pseudo code:
#def invert_tree(nodes, root)
#Stop recursion if tree is empty
#swap left subtree with right subtree
#invert left subtree
#invert right subtree
Solution 1:[1]
I found an answer
nodes = [[4], [7, 2], [1, 3, 6, 9]]
Recursive
newlist1 = []
def reverse_tree(lst):
if not lst:
return
newlist1.append(lst.pop(0)[::-1])
reverse_tree(lst)
reverse_tree(nodes)
print(newlist1)
Output:
[[4], [2, 7], [9, 6, 3, 1]]
Using list comprehension
#ListComprehension
newlist2 = [x[::-1] for x in nodes]
print(newlist2)
Output:
[[4], [2, 7], [9, 6, 3, 1]]
Solution 2:[2]
Your question isn't clear;
From what I understood:
To print the nodes of an inverted tree:
Try Level order traversal, more precisely you can use the BFS method.
OR: If you want to invert a Binary tree; My approach (given the root node of the tree):
def invert_tree(self, root):
if root:
temp=root.left
root.left = self.invert_tree(root.right)
root.right = self.inver_tree(temp)
return root
Since, every node in the tree in visited once, the time complexity is O(n).
Solution 3:[3]
TreeNode* Invert(TreeNode* tree) {
if(tree == NULL) return NULL;
TreeNode* temp;
temp = tree->left;
tree->left = tree->right;
tree->right = temp;
Invert(tree->left);
Invert(tree->right);
return tree;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | mhpd |
| Solution 3 | jaaaaaaaaaavid |

