python 数据结构与算法——树的概念、二叉树的概念

一、树的概念

B的节点的度为3,G的节点的度为2

树的度为3

K、J、F、L、O、P 为叶节点

E的父节点为B

D、E、F为兄弟节点

A为第一层,B,C为第二层,以此类推

树的深度是5

D和H为堂兄弟节点

A、C、G、M都是O节点的祖先

G的子孙是L、M、O

完全二叉树

满二叉树

排序二叉树

顺序存储用的不多!!!!

二、二叉树的概念

编程实现:

遍历:

1、广度优先遍历

类似于队列,(右边补充元素,左边取)

树添加数据

# -*- coding: utf-8 -*-
"""
Created on Mon Feb 25 21:47:53 2019
树的添加
@author: Xavier
"""
class Node(object):
    def __init__(self,item):
        self.elem=item
        self.lchild=None
        self.rchild=None
class Tree(object):
    #二叉树
    def __init__(self):
        self.root=None
        
    def add(self,item):
        node=Node(item)
        if self.root is None:
            self.root=node
            return
        
        queue=[]
        queue.append(self.root)
        while queue:
            cur_node=queue.pop(0)
            if cur_node.lchild is None:
                cur_node.lchild=node
                return
            else:
                queue.append(cur_node.lchild)
            if cur_node.rchild is None:
                cur_node.rchild=node
            else:
                queue.append(cur_node.rchild)

猜你喜欢

转载自blog.csdn.net/zuyuhuo6777/article/details/87923837