Tree structure and algorithm

  1. Full Binary full binary tree
    if the height of the binary tree is h, the number of nodes of the book is 2 ^ h-1, h> = 0, is said this tree is a full binary tree.
  2. Complete binary tree complete binary tree
    , if the height of the binary tree is h, the number of nodes is less than the book 2 ^ h-1, numbered from top to bottom, left to right correspond. If there are N nodes, then the binary number of layers h is log (N + 1). "
  3. Oblique skewed binary tree binary tree
    no right node, left oblique binary tree.
    We did not do node, right oblique binary tree.
  4. Strictly binary strictly binary tree
    binary tree for each non-terminal node has a non-empty left and right subtrees.

Achieved by binary array

Using an ordered one-dimensional array represents a binary tree, a binary tree may first want to use this as a full binary tree, and the first layer has a k 2 ^ (k-1) nodes, in sequential one-dimensional array.

  1. Left subtree index value is the parent index value 2 *
  2. Right subtree of the parent index value is an index value of 2 + 1 *

Binary search tree features:

  1. May be empty set, if it is an empty set, then the node must have a key.
  2. Each value must be greater than a root of the value of the left subtree
  3. Each of the root value must be less than the value of the right subtree
  4. Left and right sub-tree is a binary search tree
  5. Each tree node value is not the same
# 按序输入一颗二叉树节点的数据,分别是0,6,3,5,4,7,8,9,2,并建立一颗查找树,最后输出存储此二叉树的一维数组。
def btree_create(btree, data, length):
    for i in range(1, length):
        level = 1
        while btree[level] != 0:  # 0不参与争斗,用来补位
            if data[i] > btree[level]:  # 如果原始数组内的值大于树根,则往右子树比较
                level = level * 2 + 1
            else:  # 小于等于树根,则往左子树比较
                level = level * 2
        btree[level] = data[i]  # 把数组值放进二叉树


length = 9
data = [0, 6, 3, 5, 4, 7, 8, 9, 2]
btree = [0] * 16
print("原始数组内容为:")
for i in range(length):
    print("[%2d] " % data[i], end='')
print('')
btree_create(btree, data, length)
print("二叉树内容为:")
for i in range(1, 16):
    print("[%2d] " % btree[i], end='')
print()

Achieve binary tree with chain

For easily add and delete nodes, but hard to find the parent, unless a parent field increase at each node

  • Binary Tree class declaration
class Tree:
    def __init__(self):
        self.data = 0
        self.left = None
        self.right = None
  • To list binary tree:
def create_tree(root, val):
    newnode = Tree()
    newnode.data = val
    newnode.left = None
    newnode.right = None
    if root == None:
        root = newnode
        return root
    else:
        current = root  # 父节点
        # 判断左右子树走向
        while current != None:
            backup = current  # 尾节点
            if current.data > val:
                current = current.left
            else:
                current = current.right
        # 把尾节点和当前节点值比较,把节点放进链表
        if backup.data > val:
            backup.left = newnode
        else:
            backup.right = newnode
        return root

data = [5, 6, 24, 8, 12, 3, 17, 1, 9]
ptr = None
root = None
for i in range(9):
    ptr = create_tree(ptr, data[i])
print("左边:")
root = ptr.left
while root != None:
    print("%d" %root.data)
    root = root.left or root.right
print('-----')
print("右边:")
root = ptr.right
while root != None:
    print("%d" %root.data)
    root = root.right or root.left
print()
左边:
3
1
-----
右边:
6
24
8
12
17

Traversing Binary Tree

  • Preorder (Inorder): left subtree - the root - right subtree
def inorder(ptr):
    if ptr != None:
        inorder(ptr.left)
        print("[%2d] " % ptr.data, end='')
        inorder(ptr.right)

Preorder traversal (Preorder): root - left subtree - right subtree

def preorder(ptr):
    if ptr != None:
        print("[%2d] " % ptr.data, end='')
        preorder(ptr.left)
        preorder(ptr.right)

Postorder (Postorder): left subtree - right subtree - the root

def postorder(ptr):
    if ptr != None:
        postorder(ptr.left)
        postorder(ptr.right)
        print("[2d] " % ptr.data, end='')

Find a binary tree node

def search(ptr, val):
    while True:
        if ptr == None:
            return None
        if ptr.data == val:
            return ptr
        elif ptr.data > val:
            ptr = ptr.left
        else:
            ptr = ptr.right

Insert binary tree node

if search(ptr, data) != None:
    print("二叉树中有此节点了")
else:
    ptr = create_tree(ptr, data)
    inorder(ptr)

Delete binary tree node

Leaf node is removed, as long as its parent node connected points None can
delete nodes only sub-tree
nodes removed were two sub-tree

  • In order immediate forerunner (inorder immediate predecessor): To delete a node of the left subtree greatest move up. Simply put, the left child node of the tree, looking right, know the right pointer to None, this node is a pioneer in the order immediately.
  • Now in order successor (inorder immediate successor): the minimum of the right subtree of a node to be deleted to move up. Simply put, the right child node of the tree, looking left, knowing that the left pointer to None, this node is the immediate successor in order.

    Piled tree (heap tree) sorting algorithm

    Select the sort of improvement. Piled tree is a special binary tree, the tree can be divided into a maximum and minimum accumulation accumulation tree.
  • The maximum accumulation of tree true:
    it is a complete binary tree.
    Values of all the nodes are equal to or greater than the value of its left and right child nodes.
    The accumulation of tree roots is the largest.
  • Tree meet minimum accumulation:
    it is a complete binary tree.
    Values of all the nodes is equal to or less than the value of its left and right child nodes.
    Tree roots is the accumulation of the smallest.
def heap(data, size):
    for i in range(int(size/2), 0, -1):  # 建立堆积树节点
        ad_heap(data, i, size - 1)
    print("堆积的内容:", end='')
    for i in range(1, size):
        print("[%2d ]" % data[i], end='')
    print("\n")
    for i in range(size-2, 0, -1):  # 堆积排序
        data[i+1], data[1] = data[1], data[i+1]  # 头尾节点交换
        ad_heap(data, 1, i)  # 处理剩余节点
        print("处理过程:", end='')
        for j in range(1, size):
            print("[%2d ]" % data[j], end='')
        print()


def ad_heap(data, i, size):
    j = 2 * i
    tmp = data[i]
    post = 0
    while j <= size and post == 0:
        if j < size:
            if data[j] < data[j + 1]:  # 找出最大节点
                j += 1
        if tmp >= data[j]:  # 若树根较大,则继续比较
            post = 1
        else:              # 若树根较小,则继续比较
            data[int(j/2)] = data[j]
            j = 2 * j
    data[int(j/2)] = tmp  # 指定树根为父节点

Guess you like

Origin www.cnblogs.com/catyuang/p/11760502.html