Trees

This lesson delves further into the tree data structure. The tree data structure is used to solve a lot of paths finding related problems efficiently. This chapter introduces the binary tree, tree terminologies, and tree traversal.

A tree is a non-linear data structure, consisting of nodes that are connected in a hierarchical way. Hierarchy exists everywhere. Consider the hierarchy of a company where managers report to directors, directors report to CXOs, CFOs, and CTOs, and the CMO reports to the CEO.

Every tree structure contains a tree. Each tree has one member that is the root node. There is no superior node to the root node.

Binary tree

A binary tree is a tree where each node has the following three components:

  • Key: A key or data element that contains information.
  • Left pointer: Points to the left side of the tree following a node.
  • Right pointer: Points to the right side of the tree following a node.
  • Press + to interact
    class TreeNode:
    #Initialize the tree
    def __init__(self, key):
    self.left = None
    self.right = None
    self.key = key
    def print_node_info(self):
    print(self.key)
    root = TreeNode('Root')
    root.print_node_info()

    In the above code we have created a TreeNode class which contains the structure of a binary tree. It contains a left pointer, a right pointer, and a data ...