An implementation example of a python binary tree

  • 2020-04-02 13:11:32
  • OfStack

The definition of the tree

A tree is an important nonlinear data structure. Intuitively, it is a structure of data elements (called nodes in a tree) organized by branching relationships, much like trees in nature. Tree structure exists widely in the objective world, such as the genealogy of human society and various social organizations can be represented by tree image. Trees are also widely used in the computer world. For example, when compiling a source program, a tree can be used to represent the syntax structure of the source program. For example, in database system, tree structure is one of the important forms of information organization. All problems with hierarchical relationships can be described by tree.
The characteristic of tree structure is that every node can have more than one direct successor, and all nodes except the root have only one direct precursor.
The recursive definition of a tree is as follows :(1) there is at least one node (called the root) and (2) the others are mutually disjoint subtrees

Binary tree:
Binary tree is an ordered tree with a finite set of n (n p 0) nodes and at most two subtrees per node. It is either an empty set, or it consists of a root and two disjoint binary trees called left and right subtrees.

Binary tree Features:
(1) binary trees are ordered trees. Even if there is only one subtree, the left and right subtrees must be distinguished.
(2) the degree of each node of the binary tree cannot be greater than 2, and it can only be one of 0, 1 and 2.
(3) there are five forms of all nodes in binary trees: nil, nodes without left and right subtrees, nodes with only left subtree, nodes with only right subtree and nodes with left and right subtrees.

The basic data structure of binary trees


#!/usr/bin/python
# -*- coding: utf-8 -*-
class TreeNode(object):
    def __init__(self,data,left,right):
        self.data = data
        self.left = left
        self.right = right

class BTree(object):
    def __init__(self,root=0):
        self.root = root


Related articles: