Python binary tree implementation example

Source: Internet
Author: User

Tree Definition

A tree is an important non-linear data structure. It is a structure in which data elements (called nodes in a tree) are organized by branches, just like trees in nature. Tree structures are widely used in the objective world, such as the genealogy of human society and various social organizations. Tree is also widely used in the computer field. For example, when compiling a source program, a tree can be used to represent the syntax structure of the source program. Another example is that tree structure is also an important form of information organization in database systems. All hierarchical issues can be described in a tree.
The tree structure features that each of its nodes can have more than one direct successor. All nodes except the root node have only one direct precursor.
The recursive definition of a tree is as follows: (1) there must be at least one node (called the root) (2) other child trees that are not mutually exclusive

Binary Tree: 
A binary tree is a finite set of n (n ≥ 0) nodes. Each node has a maximum of two Subtrees. It is either an empty set, or a root tree and two non-overlapping Binary Trees called left and right subtree.

Binary TreeFeatures:
(1) A binary tree is an ordered tree. Even if there is only one subtree, the left and right Subtrees must be differentiated;
(2) The degree of each node of a binary tree cannot be greater than 2, and only one of 0, 1, and 2 can be used;
(3) there are five types of nodes in a binary tree: empty node, no left and right subtree node, only left subtree node, only right subtree node and left and right subtree node.

Basic Data Structure of a binary tree

Copy codeThe Code is as follows:
#! /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 Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.