Tree, tree traversal and heap sort

A tree base

Definition 1 tree

1 two definitions of ways

Tree: nonlinear structure

1 tree is a set n (n> = 0) elements
when n = 0, called null tree
tree is only a particular node without predecessor elements, roots and tree Root referred to
the tree root in addition, the remaining elements of only one precursor, there can be zero or more follow-up, no root predecessor, only successor


2 recursive definition
tree T is a collection of elements n (0 n> =), n = 0 , the empty tree is called
its one and only one particular element and roots, the remaining elements may be divided into m disjoint collection, T1, T2, T3 ... Tm , and each set is a tree, known as sub-tree of subtree T, which also has its own subtree rooted

The term cluster number 2

Precursor: element ahead of the current node
after flooding: the node element after the current
node: data element in the tree
of the node degree: number of nodes has degree subtree called, denoted d (v)
leaf node: node is 0 degree point, called a leaf node, the terminating node, the end node
branch node: node degree is not 0, the non-terminal node is called a branch node or a
branch: the relationship between the nodes, and connecting
internal node: a branch other than the root node, leaf nodes excluding of course, and pinch head to tail, leaving the middle
of the trees: tree degree is the maximum value of the respective nodes.


Children (son child) nodes: the root of sub-tree node called the children of the node
parent (parent Parent) node: a node that is the root of each subtree parents.
Brothers (sibling) node: node having the same parent node
ancestor node: the node from the root node to all nodes on the branch is
descendants as: all sub-tree nodes are called node is a descendant
level nodes: the root node of the first layer, the second layer is a child of the root node, and so on, designated as L (v)
tree depth (height depth): the maximum level of the tree
cousins : parent node in the same layer.

Ordered tree: the sub-tree nodes are ordered (size brothers with the order), can not exchange
unordered tree: the sub-tree nodes are unordered, can be exchanged


Path: K tree nodes n1, ... nk N2, meet ni is n (i + 1) of the parent, a path is referred to n1, nk, is a string down the line, it is after a previous parent (precursor) node

Path length = length - 1 node in the path, and the number of branches

Forest: disjoint tree m (m> = 0) trees
for the nodes, the set of subtrees which is forest,

3 tree features:

A unique root
sub-tree disjoint
3 except the root, each element can have only one precursor, can have zero or more subsequent
4 root has no parent node (precursor), there is no leaf node child nodes (successor )
5 vj vi is the parents, then L (vi) = L (vj ) -1, that is less than the level of the parents of the child node 1

2 binary concept

1 Features

Each node 1 up to 2 subtree
binary node of degree greater than 2 absent
2 which is an ordered tree, left subtree, right subtree is the order, the order can not exchange
3 even if a certain node is only one subtree, We have to determine whether it is left or right subtree subtree

Five Patterns 2 binary tree

Empty binary 1
2 is only one root node
3 only the left sub-tree root node
4 only the right subtree of the root
5 and the root node with a left subtree right subtree

3 oblique tree

Tree, tree traversal and heap sort

Left oblique tree: all nodes have only left subtree
right oblique tree: all nodes have only the right subtree

4 full binary tree

Tree, tree traversal and heap sort

All branches of the nodes of a binary tree there are left and right sub-tree sub-tree, and all the leaf nodes exist only in the bottom layer.
Binary same depth, up to a full binary tree node
k depth (1 <= k <= n ), the total number of nodes is 2 ** (k) -1

5 full Nimata 树

Tree, tree traversal and heap sort

If the depth of the binary tree is k, the number of layers in the binary tree from a node to the k-1 layer are hit the maximum number, all the nodes in the k-th layer are concentrated in the left, which is complete binary tree
complete binary tree by a full binary lead
full binary tree must be a complete binary tree, but not necessarily a complete binary tree is a full binary tree
k depth (1 <= k <= n ), the maximum total number of nodes is 2 ** k-1, when the maximum time It is a full binary tree

Property 3 binary tree

1 on the i-th layer in the binary tree has up to 2 ** i-1 nodes (i> = 1)

2 binary tree of depth k, at most 2 ** k -1 nodes (k> = 1)

3 for any one binary tree T, if its end nodes is n0, a node of degree 2 is n2, there is n0 = n2 + 1, -1 = the number of nodes and the leaf nodes of degree 2.

证明:
总结点数为n=n0+n1+n2,其中n0为度数为0的节点,及叶子节点的数量,n1为度数为1 的节点的数量,n2为节点为2度数的数量。
一棵树的分支数为n-1,因为除了根节点外,其余结点都有一个分支,及n0+n1+n2-1
分支数还等于n0*0+n1*1+n2*2及 n1+2n2=n-1
可知 2*n2+n1=n0+n1+n2-1 及就是 n2=n0-1


4 高度为k的二叉树,至少有k个节点
5 具有n个节点的完全二叉树的深度为int(log2n)+1 或者 math.ceil(log2(n+1))

6 有一个n个节点的完全二叉树, 结点按照层序编号,如图

Tree, tree traversal and heap sort

如果i=1,则节点i是二叉树的根,无双亲,如果i>1,则其双亲为int(i/2),向下取整。就是叶子节点的编号整除2得到的就是父节点的编号,如果父节点是i,则左孩子是2i,若有右孩子,则右孩子是2i+1,。
如果2i>n,则结点i无左孩子,及结点为叶子结点,否则其左孩子节点存在编号为2i。

如果2i+1>n,则节点i无右孩子,此处未说明是否不存在左孩子,否则右孩子的节点存在编号为2i+1。

二 二叉树遍历

1 遍历方式

遍历: 及对树中的元素不重复的访问一遍,又称为扫描

1 广度优先遍历

一次将一层全部拿完,层序遍历

Tree, tree traversal and heap sort
及 1 2 3 4 5一层一层的从左向右拿取

2 深度优先遍历

设树的根结点为D,左子树为L,右子树为R。且要求L一定要在R之前,则有下面几种遍历方式

1 前序遍历,也叫先序遍历,也叫先跟遍历,DLR
Tree, tree traversal and heap sort
1-2-4-5-3-6
2 中序遍历,也叫中跟遍历, LDR
Tree, tree traversal and heap sort
4-2-5-1-6-3
3 后序遍历,也叫后跟遍历,LRD
Tree, tree traversal and heap sort
4-5-2-6-3-1

三 堆排序

1 堆定义

1 堆heap 是一个完全二叉树
2 每个非叶子结点都要大于或等于其左右孩子结点的值称为大顶堆

Tree, tree traversal and heap sort

3 每个非叶子结点都要小于或者等于其左右孩子结点的值称为小顶堆

Tree, tree traversal and heap sort

4 根节点一定是大顶堆的最大值,小顶堆中的最小值

2 堆排序

1 构建完全二叉树

1 待排序数字为 49 38 65 97 76 13 27 49

2 构建一个完全二叉树存放数据,并根据性质5对元素进行编号,放入顺序的数据结构中

Tree, tree traversal and heap sort

3 构造一个列表为 [0,49,38,65,97,76,13,27,49]的列表

2 构建大顶堆

1 度数为2的结点,如果他的左右孩子最大值比它大,则将这个值和该节点交换
2 度数为1 的结点,如果它的左孩子的值大于它,则交换
3 如果节点被置换到新的位置,则还需要和其孩子节点重复上述过程

3 构建大顶堆--起点选择

Tree, tree traversal and heap sort

1 从完全二叉树的最后一个结点的双亲开始,及最后一层的最右边的叶子结点的父结点开始
2 结点数为n,则起始节点的编号为n//2(及最后一个结点的父节点)

4 构建大顶堆--下一个节点的选择

从起始节点开始向左寻找其同层节点,到头后再从上一层的最右边节点开始继续向左逐步查找,直到根节点

Tree, tree traversal and heap sort

5 大顶堆目标

确保每个结点的都比其左右结点的值大

Tree, tree traversal and heap sort
第一步,调换97和38,保证跟大

Tree, tree traversal and heap sort
第二步,调换49和97

Tree, tree traversal and heap sort
第三步,调换76和49

Tree, tree traversal and heap sort
第四步,调换38和49

此时大顶堆的构建已经完成

3 排序

将大顶堆根节点这个最大值和最后一个叶子节点进行交换,则最后一个叶子节点成为了最大值,将这个叶子节点排除在待排序节点之外,并从根节点开始,重新调整为大顶堆,重复上述步骤。

Tree, tree traversal and heap sort
Tree, tree traversal and heap sort
Tree, tree traversal and heap sort
Tree, tree traversal and heap sort
Tree, tree traversal and heap sort
Tree, tree traversal and heap sort
Tree, tree traversal and heap sort

四 实战和代码

1 打印树

l1=[1,2,3,4,5,6,7,8,9]
打印结果应当如下

Tree, tree traversal and heap sort

思路:可通过将其数字映射到下方的一条线上的方式进行处理及就是 8 4 9 2 0 5 0 1 0 6 0 3 0 7 0 的数字,其之间的空格可以设置为一个空格的长度,其数字的长度也可设置为固定的2,则

Tree, tree traversal and heap sort

则第一层第一个数字据前面的空格个数为7个,据后面的空格也是7个,
第二层第一个数字据前面的空格个数为3个,第二个数字距离后面的空格也是3个,
第三层据前面的空格为1,第三层最后一个据后面的空格也是1,
第四层据前面的空格是0,第四层最后一个据后面的空格也是0,
现在在其标号前面从1开始,则层数和空格之间的关系是

1 7
2 3
3 1
4 0
转换得到
4 7
3 3
2 1
1 0

及就是 2**(l-1) -1 l 表示层数
间隔关系如下
1 0
2 8
3 4
4 2
转换得到
4 0
3 8
2 4
1 2
及就是 2**l其中l 表示层数。

代码如下

import  math 
# 打印二叉树
def  t(list):
    '''
    层数      层数取反(depth+1-i,depth表示总层数,此处为4,i表示层数)   据前面的空格数            间隔数        每层字数为
    1            4                                                              7                     0              1
    2            3                                                              3                     7              2
    3            2                                                              1                     3              4
    4            1                                                              0                     1              8
                                                                    (2**(depth-i)-1)      (2**(depth-i)-1)        (2**i)   

    层数和数据长度的关系是 n表示的是数据长度
    1     1  
    2-3   2   
    4-7   3
    8-15  4       
    2**(i-1)<num<(2**i)-1,及就是int(log2n) +1 及 math.ceil(log2n)
    '''
    index=1
    depth=math.ceil(math.log(len(list),2))    #此处获取到的是此列表转换成二叉树的深度,此处前面插入了一个元素,保证列表和二叉树一样,其真实数据都是从1开始
    sep='  ' # 此处表示数字的宽度 
    for  i in range(depth):
        offset=2**i #每层的数字数量1  2  4  8  
        print (sep*(2**(depth-i-1)-1),end="")  # 此处取的是前面空格的长度
        line=list[index:index+offset] #提取每层的数量
        for  j,x  in enumerate(line):
            print ("{:>{}}".format(x,len(sep)),end="") # 此处通过format来获取其偏移情况,第一个x表示其大括号中的内容,第二个表示偏移的程度
            interval= 0  if  i ==0  else  2**(depth-i)-1  # 此处获取到的是间隔数,当值大于1时,满足如此表达式
            if  j < len(line)-1: #选择最后一个时不打印最后一个的后面的空格,及就是1,3,7后面的空格
                print (sep*interval,end="")
        index += offset
        print ()

结果如下
Tree, tree traversal and heap sort

2 堆排序算法实现

# 构建一个子树的大顶堆
def  heap_adjust(n,i,array):
    '''
    调整当前结点(核心算法)
    调整的结点的起点在n//2(二叉树性质5结论),保证所有调整的结点都有孩子结点
    :param  n : 待比较数个数
    :param  i : 当前结点下标
    :param array : 待排序数据
    :return : None
    '''
    while  2*i<=n: # 孩子结点判断,2i为左孩子,2i+1为右孩子 
        lchile_index= 2*i  #选择结点起始并记录 n=2*i-1,因为其是从0开始,因此只有len()-1
        max_child_index=lchile_index  
        # 判断左右孩子的大小,并将大的赋值给max_child_index 
        if  n > lchile_index  and  array[lchile_index+1] > array[lchile_index]: #说明其有右孩子,且右孩子大于左孩子 
            max_child_index=lchile_index+1  #n=2i+1 # 此时赋值的是下标
        # 判断左右孩子的最大值和父结点比较,若左右结点的最大值大,则进行交换
        if  array[max_child_index] > array[i]:  #此处的i是父节点,通过和父节点进行比较来确认其最大,
            array[i],array[max_child_index]=array[max_child_index],array[i]
            i= max_child_index   #右子节点的下标会赋值到父结点,并将其值赋值到父结点,
        else:
            break 
# 构建所有的大顶堆传入参数
def  max_heap(total,array):
    for i in range(total//2,0,-1):  #构建最后一个叶子结点的父结点
        heap_adjust(total,i,array)  #传入总长和最后一个叶子结点的父结点和数列
        print  (t(array))
    return  array
#构建大顶堆,起点选择    
def  sort(total,array):    # 此处起点是1,因此必须在前面添加一个元素,以保证其位置编号和树相同
    while  total>1:
        max_heap(total,array)
        array[1],array[total]=array[total],array[1]  #将最后一个结点和第一个结点调换,
        total-=1
    return array

结果如下
Tree, tree traversal and heap sort

3 总结

Heap sort Heap Sort sorting with a selected stack nature, selected in the top of the stack the maximum or minimum
time complexity
time complexity heap sort is O (nlog2 n), since the state of the original recording stack Sort not sensitive, and therefore whether it is the best and the worst average time complexity are O (nlog2 n)

Space complexity
except for using an exchange space, the space complexity is O (1)
Stability of
sorting algorithms unstable

Guess you like

Origin blog.51cto.com/11233559/2401524