Python data structure and algorithm - tree, binary tree

Basic concepts

1. Definitions: tree (Tree) is n (n≥0) a limited set of nodes T, which satisfies two conditions: one and only one specific called the root (Root) nodes; the remaining nodes can be divided into m (m≥0) disjoint finite set T1, T2, ......, Tm, wherein each set is a tree, and said its subtree rooted (subtree).

2. Basic Concepts

  • Number subtree of a node is called the degree of the node, a tree degree is the maximum degree of the nodes in the tree.
  • Leaf nodes are called zero degree or terminal nodes, called nodes is not zero degree branch node, branch nodes except the root node is referred to as internal.
  • A sub-tree of the root node is called a child node of the node, this node is called a parent node thereof, referred to as sibling nodes among the respective sub-nodes in the same node. A tree root node has no parent node, leaf node has no children.
  • A series node k1, k2, ......, ki, ki + 1, ......, kj, and satisfies ki ki + 1 is the parent node, called a path from k1 to kj, the length of the path of j-1 , i.e., the number of edges in the path. Path behind the previous node is an ancestor of a node, the node is behind the front descendant nodes.
  • Layers of the node to a parent node plus a number of layers, the number of layers is defined as a root node. The maximum number of layers in the tree is called a node height or depth of the tree.
  • Set m (m≥0) disjoint trees called forest trees. Remove the tree root to become forest, forest add a new root node becomes a tree.

Binary Tree

The definition and characteristics

1. Definitions: Binary Tree (Binary Tree) is a finite set of n (n≥0) nodes, or it is an empty set (n = 0), or is a root node and two disjoint, called binary left subtree and right subtree composition. Different from ordinary binary ordered tree, binary tree strict distinction between left and right child child, even if only one child node should distinguish between left and right.

2. Binary Tree features

  • Binary tree of nodes on level i (i≥1) up to 2 ^ {}. 1 I- 2 I - . 1 th.
  • 深度为k(k≥1)的二叉树最多有2^k-12k1个节点。
  • 在任意一棵二叉树中,树叶的数目比度数为2的节点的数目多一。
  • 满二叉树 :深度为k(k≥1)时有2^k-12k1个节点的二叉树。
  • 完全二叉树 :只有最下面两层有度数小于2的节点,且最下面一层的叶节点集中在最左边的若干位置上。

二叉树的遍历

遍历 :沿某条搜索路径周游二叉树,对树中的每一个节点访问一次且仅访问一次。

先序遍历: 先访问树根,再访问左子树,最后访问右子树;
中序遍历: 先访问左子树,再访问树根,最后访问右子树;
后序遍历: 先访问左子树,再访问右子树,最后访问树根;
层次遍历: 从根节点开始,逐层从左向右进行遍历。

递归思想和实践

1.什么是递归?

所谓递归函数是指一个函数的函数体中直接调用或间接调用了该函数自身的函数。这里的直接调用是指一个函数的函数体中含有调用自身的语句,间接调用是指一个函数在函数体里有调用了其它函数,而其它函数又反过来调用了该函数的情况。

2.递归函数调用的执行过程分为两个阶段

递推阶段:从原问题出发,按递归公式递推从未知到已知,最终达到递归终止条件。
回归阶段:按递归终止条件求出结果,逆向逐步代入递归公式,回归到原问题求解。

3.优点与缺点

优点:递归可以把问题简单化,让思路更为清晰,代码更简洁
缺点:递归因系统环境影响大,当递归深度太大时,可能会得到不可预知的结果

# 求n的阶乘
def recursion(n):
  # 递归终止条件
  if n < 1:
    return 1
  return n * recursion(n - 1)

print("n!=",recursion(5))

二叉树的代码实现

二叉树顺序存储

二叉树本身是一种递归结构,可以使用Python list 进行存储。但是如果二叉树的结构比较稀疏的话浪费的空间是比较多的。

  • 空结点用None表示
  • 非空二叉树用包含三个元素的列表[d,l,r]表示,其中d表示根结点,l,r左子树和右子树。
 1 ['A',['B',None,None
 2      ],
 3      ['C',['D',['F',None,None],
 4                ['G',None,None],
 5           ],     
 6           ['E',['H',None,None],
 7                ['I',None,None],
 8           ],
 9      ]
10 ]
顺序存储代码
 1 bitree.py 二叉树的实现
 2 
 3 思路分析: 
 4 1. 使用链式存储
 5   节点类设计上有两个属性变量引用左孩子和右孩子
 6 2. 操作类完成二叉树的遍历
 7 """
 8 from day2.squeue import SQueue
 9 
10 # 二叉树节点
11 class TreeNode:
12   def __init__(self, data=None, left=None, right=None):
13     self.data = data
14     self.left = left
15     self.right = right
16 
17 #  二叉树操作
18 class Bitree:
19   def __init__(self, root=None):
20     self.root = root  # 获取树根
21 
22   # 先序遍历
23   def preOrder(self,node):
24     if node is None:
25       return
26     print(node.data,end=' ')
27     self.preOrder(node.left)
28     self.preOrder(node.right)
29 
30   #  中序遍历
31   def inOrder(self, node):
32     if node is None:
33       return
34     self.inOrder(node.left)
35     print(node.data, end=' ')
36     self.inOrder(node.right)
37 
38   #  后序遍历
39   def postOrder(self, node):
40     if node is None:
41       return
42     self.postOrder(node.left)
43     self.postOrder(node.right)
44     print(node.data, end=' ')
45 
46   # 层次遍历
47   def levelOrder(self,node):
48     sq = SQueue()
49     sq.enqueue(node) # 从node遍历
50     while not sq.is_empty():
51       node = sq.dequeue() # 出队一个
52       print(node.data,end=' ') # 遍历数据
53       if node.left:
54         sq.enqueue(node.left)
55       if node.right:
56         sq.enqueue(node.right)
57 
58 if __name__ == "__main__":
59   #  后序遍历 BFGDIHECA
60   # 构建树 (笔记中)
61   b = TreeNode('B')
62   f = TreeNode('F')
63   g = TreeNode('G')
64   d = TreeNode('D', f, g)
65   i = TreeNode('I')
66   h = TreeNode('H')
67   e = TreeNode('E', i, h)
68   c = TreeNode('C', d, e)
69   a = TreeNode('A', b, c)  # 树根
70 
71   #  初始化树对象,得到树根
72   bt = Bitree(a)
73   # 先序
74   bt.preOrder(bt.root)
75   print()
76   #  中序
77   bt.inOrder(bt.root)
78   print()
79   bt.postOrder(bt.root)
80   print()
81   bt.levelOrder(bt.root)
82   print()
链式存储代码

 

Guess you like

Origin www.cnblogs.com/maplethefox/p/10988684.html