Search code examples
pythonbinary-tree

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:

enter image description here

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

  • 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]]