Vinicius Vasconcelos
Vinicius Vasconcelos

Reputation: 140

Construct String from Binary Tree

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 :)

Upvotes: 0

Views: 294

Answers (1)

Zalak Bhalani
Zalak Bhalani

Reputation: 1144

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) + ')')

Upvotes: 1

Related Questions