0

A bit of a newbie to computing science.

I have the basics for a binary tree in Python:

class TreeBinary:
 def __init__(self, data):
 self.data = data
 self.left = None
 self.right = None

This works well on insertion to popularize the tree:

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

One of the challenges that I am trying to discover is how to print this tree in order to show the sub-trees if there is one in the following model:

(1 (2 () ()) (3 () (4 () ())))
(2 () ())
(3 () (4 () ()))

I was able to print, but not in this format with these spaces between the sub-trees:


def show_aux(root):
 if not root:
 return ''
 string = str(root.data)
 if root.left or root.right:
 string += '(' + show_aux(root.left) + ')'
 else:
 string += '('
 string += ')'
 if root.right:
 string += '(' + show_aux(root.right) + ')'
 else:
 string += '('
 string += ')'
 return string
def show(root):
 print('(' + show_aux(root) + ')')

My results are coming out this way:

(1(2()())(3()(4()())))
(2()())
(3()(4()()))

I would like a direction to print in the expected format with the spaces between the sub-trees.

Thanks :)

asked Apr 29, 2021 at 6:47

1 Answer 1

1

Add spaces before every ( like this

def show_aux(root):
 if not root:
 return ''
 string = str(root.data)
 if root.left or root.right:
 string += ' (' + show_aux(root.left) + ')' #Space before '('
 else:
 string += ' (' #Space before '('
 string += ')'
 if root.right:
 string += ' (' + show_aux(root.right) + ')' #Space before '('
 else:
 string += ' (' #Space before '('
 string += ')'
 return string
def show(root):
 print('(' + show_aux(root) + ')')
answered Apr 29, 2021 at 6:53
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks. Seeing now I realize that the solution was right before my eyes.
Yes . You just needs to improve logic.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.