Skip to content

Instantly share code, notes, and snippets.

@pnkfelix
Last active May 6, 2023 11:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pnkfelix/954bdc3a4fe1ed3413effb1f7e2630bb to your computer and use it in GitHub Desktop.
Save pnkfelix/954bdc3a4fe1ed3413effb1f7e2630bb to your computer and use it in GitHub Desktop.

New chat Today Print Binary Tree.

User How print a binary tree to stdout?

ChatGPT To print a binary tree to stdout, you can use a recursive approach that traverses the tree and prints the values of each node in a particular order. Here's an example implementation in Python:

class Node:
    def __init__(self, val=None, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right

def print_tree(root, level=0):
    if root is not None:
        print_tree(root.right, level=level+1)
        print(' ' * 4 * level + '->', root.val)
        print_tree(root.left, level=level+1)

This implementation assumes that each node in the binary tree is an instance of the Node class, which has a val attribute for the value of the node, and left and right attributes for the left and right children of the node, respectively.

The print_tree function recursively prints the right subtree, then the current node, and then the left subtree, with each node indented by a multiple of 4 spaces depending on its depth in the tree. The level argument is used to keep track of the depth of the current node.

To use this function, you can create a binary tree by creating instances of the Node class and setting the left and right attributes as appropriate, and then call print_tree with the root of the tree as the argument. For example:

root = Node(1, Node(2), Node(3, Node(4), Node(5)))
print_tree(root)

This would print the following output:

        -> 5
    -> 3
        -> 4
-> 1
        -> 2

User I want to have labels on the interior nodes of the tree, and lines connecting each child to its parent in the output

ChatGPT To print a binary tree with labels on the interior nodes and lines connecting each child to its parent, you can modify the previous implementation by passing an additional argument to the print_tree function that keeps track of the parent node, and then printing the appropriate labels and lines accordingly.

Here's an updated implementation in Python:

class Node:
    def __init__(self, val=None, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right

def print_tree(node, parent=None, is_left=True, indent=4):
    if node is not None:
        direction = 'left' if is_left else 'right'
        label = '' if parent is None else f'({direction}, {parent.val})'
        print_tree(node.right, node, False, indent + 4)
        print(' ' * indent, label, '->', node.val)
        print_tree(node.left, node, True, indent + 4)

This implementation also assumes that each node in the binary tree is an instance of the Node class.

The print_tree function now takes four arguments: node is the current node being printed, parent is the parent node of node, is_left is a boolean that indicates whether node is the left child of parent, and indent is the number of spaces to indent each level of the tree.

The function first recursively prints the right subtree, passing the current node as the new parent argument and setting is_left to False to indicate that the current node is the right child of its parent. It then prints the current node, including its label if it has a parent, and then recursively prints the left subtree, passing the current node as the new parent argument and setting is_left to True to indicate that the current node is the left child of its parent.

To use this function, you can create a binary tree as before, and then call print_tree with the root of the tree as the argument. For example:

root = Node(1, Node(2), Node(3, Node(4), Node(5)))
print_tree(root)

This would print the following output:

              -> 5
          (right, 3) -> 3
              -> 4
(left, 1) -> 1
          -> 2

The output shows the labels of each interior node in parentheses, and lines connecting each child to its parent. The direction of each line is indicated by the label, which shows whether the child is the left or right child of its parent.

User I want the left child to be printed below its parent, but on the same column, and the right child to be printed on the same line, to the right of its parent. Can you do that instead?

ChatGPT Sure, to print the left child below its parent and the right child to the right of its parent, you can modify the print_tree function to keep track of the position of each node, and use that information to adjust the indentation of the child nodes accordingly.

Here's an updated implementation in Python:

class Node:
    def __init__(self, val=None, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right

def print_tree(node, pos=0, level=0, markers=None):
    if node is not None:
        if markers is None:
            markers = {}  # stores the position of each node

        print_tree(node.right, pos+1, level+1, markers)
        marker = markers.get(level, pos)
        spacing = marker - pos
        print(' ' * (spacing * 3 + 1), end='')

        if pos <= marker:
            print(f'{node.val}')
        else:
            print(f'/{node.val}')

        markers[level] = pos  # update position of parent node
        print_tree(node.left, pos-1, level+1, markers)

This implementation also assumes that each node in the binary tree is an instance of the Node class.

The print_tree function now takes three arguments: node is the current node being printed, pos is the horizontal position of the node relative to its parent, and level is the depth of the node in the tree. It also takes an optional markers dictionary that keeps track of the position of each node in the current level.

The function first recursively prints the right subtree, passing pos+1 to indicate that the right child should be printed one position to the right of its parent. It then calculates the position of the current node relative to its parent, based on the position of the parent node and the position of the current node in the current level. It prints the appropriate number of spaces to align the current node with its parent, and then prints the value of the current node either on the same line or on the line below, depending on its position relative to its parent. It updates the markers dictionary with the position of the current node, and then recursively prints the left subtree, passing pos-1 to indicate that the left child should be printed one position to the left of its parent.

To use this function, you can create a binary tree as before, and then call print_tree with the root of the tree as the argument. For example:

root = Node(1, Node(2), Node(3, Node(4), Node(5)))
print_tree(root)

This would print the following output:

          1
      /       \
    2           3
              /   \
            4       5

The output shows the left child below its parent, and the right child to the right of its parent, as requested.

User I’m sorry, when I said I wanted the right child to be on the same line, I meant as the same line as its parent. So the left child ends up below the parent (in the same column as the parent), and the right child is on the same line as the parent (but in a different column). Can you do that?

ChatGPT Sure, here's an updated implementation of the print_tree function that aligns the left child below its parent and the right child to the right of its parent, on the same line:

class Node:
    def __init__(self, val=None, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right

def print_tree(node, depth=0, last_node=None):
    if node is not None:
        print_tree(node.right, depth+1, last_node=node)

        print("    " * depth, end="")
        if last_node is not None and last_node.left is not None:
            print("┌───", end="")
        else:
            print("───", end="")
        print(node.val)

        if last_node is not None and last_node.right is not None:
            print_tree(node.left, depth+1, last_node=node)
        else:
            print_tree(node.left, depth+1, last_node=None)

This implementation also assumes that each node in the binary tree is an instance of the Node class.

The print_tree function now takes three arguments: node is the current node being printed, depth is the depth of the current node in the tree, and last_node is the last node printed at the same depth (i.e., the parent of the current node). It uses the depth argument to determine how many spaces to print before the node value, and it uses the last_node argument to determine whether the current node is a left child or a right child, and to determine whether to print the connecting line to the parent node.

The function first recursively prints the right subtree, passing depth+1 and last_node=node to indicate that the current node is the parent of the right subtree. It then prints the current node value and the connecting line to the parent node, using last_node to determine the type of line to print. If the current node is a right child, it calls print_tree recursively on the left subtree with last_node=node, indicating that the current node is the parent of the left subtree. Otherwise, it calls print_tree recursively on the left subtree with last_node=None, indicating that the current node is not the parent of the left subtree.

To use this function, you can create a binary tree as before, and then call print_tree with the root of the tree as the argument. For example:

root = Node(1, Node(2), Node(3, Node(4), Node(5)))
print_tree(root)

This would print the following output:

    ┌───3
    │   ├───5
1───┤
    │   ┌───4
    └───2

The output shows the left child aligned below the parent node, and the right child aligned to the right of the parent node on the same line, as requested.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment