Reprint: binary tree traversal algorithm

Original link: https://blog.csdn.net/u013632755/article/details/102763152
Reprint: This article link: https://blog.csdn.net/u013632755/article/details/102763152

Foreword

Binary tree traversal is from the root trigger, according to a certain order in order to access all the nodes in a binary tree.
Since Unlike linear structure, to achieve a binary tree node to choose the order of the two child nodes, there are many ways to traverse all.

Binary tree traversal methods

There are many binary tree traversal, so as to traverse way of introduction, we agreed to traverse from left to right.
We need to traverse the tree structure as follows:
Here Insert Picture Description
The following traversal algorithm implemented in Python, Python students will not have to worry about, because the algorithm logic is simple.
We look at the definition of node objects:

class TreeNode:
<span class="token keyword">def</span> <span class="token function">__init__</span><span class="token punctuation">(</span>self<span class="token punctuation">,</span> data<span class="token punctuation">)</span> <span class="token operator">-</span><span class="token operator">&gt;</span> <span class="token boolean">None</span><span class="token punctuation">:</span>
    self<span class="token punctuation">.</span>data <span class="token operator">=</span> data  <span class="token comment"># 数据</span>
    self<span class="token punctuation">.</span>left <span class="token operator">=</span> <span class="token boolean">None</span>  <span class="token comment"># 左子节点</span>
    self<span class="token punctuation">.</span>right <span class="token operator">=</span> <span class="token boolean">None</span>  <span class="token comment"># 右子节点</span>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

Preorder traversal

Here Insert Picture Description
Preorder traversal algorithm, recursive, first determine whether the node is empty, if empty return. Prints the current node, and then sequentially and recursively all left child, then followed recursively all right child. Traversal order: ABDGHCEIF
recursive algorithm is as follows:

def pre_order_traverse(_binary_tree):
    """
    前序遍历
    :param _binary_tree: 二叉树
    :type _binary_tree: TreeNode
    """
    if _binary_tree is None:
        return
    print(_binary_tree.data, end='')
    pre_order_traverse(_binary_tree.left)
    pre_order_traverse(_binary_tree.right)

  
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

Preorder

Here Insert Picture Description
Inorder traversal algorithm, recursive, first determine whether the node is empty, if empty return. First sequentially and recursively all left child, then print the contents of the current node, then recursively all right child.
Traversal order: GDHBAEICF
recursive algorithm is as follows:

def in_order_traverse(_binary_tree):
    """
    中序遍历
    :param _binary_tree: 二叉树
    :type _binary_tree: TreeNode
    """
    if _binary_tree is None:
        return
    in_order_traverse(_binary_tree.left)
    print(_binary_tree.data, end='')
    in_order_traverse(_binary_tree.right)

  
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

Postorder

Here Insert Picture Description
Postorder traversal algorithm, recursive, first determine whether the node is empty, if empty return. First sequentially and recursively all left child, then recursively all right child, and finally print the contents of the current node.
Traversal order: GHDBIEFCA
recursive algorithm is as follows:

def post_order_traverse(_binary_tree):
    """
    后序遍历
    :param _binary_tree: 二叉树
    :type _binary_tree: TreeNode
    """
    if _binary_tree is None:
        return
    post_order_traverse(_binary_tree.left)
    post_order_traverse(_binary_tree.right)
    print(_binary_tree.data, end='')

  
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

By layer traversal

Here Insert Picture Description
按层遍历算法,我们将每层所有节点作为列表,传入函数进行递归,先传入列表是否为空,如果为空则返回。声明一个下一层级的子集列表。依次循环当前传入的节点列表,并打印节点数据,将当前节点左节点添加到下一层级的子集列表中,然后添加右节点。
最终遍历顺序为:ABCDEFGHI
递归算法如下:

def layer_order_traverse(_layer_nodes):
    """
    按层遍历
    :param _layer_nodes: 当前层节点集合
    :type _layer_nodes: list
    """
    if _layer_nodes is None or len(_layer_nodes) == 0:
        return
    _childs = []  # 子集
    for _node in _layer_nodes:  # 遍历传入的当前层所有节点
        print(_node.data, end='')
        if _node.left:
            _childs.append(_node.left)
        if _node.right:
            _childs.append(_node.right)
    layer_order_traverse(_childs)

  
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16

代码

class TreeNode:
<span class="token keyword">def</span> <span class="token function">__init__</span><span class="token punctuation">(</span>self<span class="token punctuation">,</span> data<span class="token punctuation">)</span> <span class="token operator">-</span><span class="token operator">&gt;</span> <span class="token boolean">None</span><span class="token punctuation">:</span>
    self<span class="token punctuation">.</span>data <span class="token operator">=</span> data  <span class="token comment"># 数据</span>
    self<span class="token punctuation">.</span>left <span class="token operator">=</span> <span class="token boolean">None</span>  <span class="token comment"># 左子节点</span>
    self<span class="token punctuation">.</span>right <span class="token operator">=</span> <span class="token boolean">None</span>  <span class="token comment"># 右子节点</span>

def fixed_tree():
“”"
返回固定二叉树结构
:return:
“”"

a = TreeNode(‘A’)
b = TreeNode(‘B’)
c = TreeNode(‘C’)
d = TreeNode(‘D’)
e = TreeNode(‘E’)
f = TreeNode(‘F’)
g = TreeNode(‘G’)
h = TreeNode(‘H’)
i = TreeNode(‘I’)
a.left = b
a.right = c
b.left = d
c.left = e
c.right = f
d.left = g
d.right = h
e.right = i
return a

def pre_order_traverse(_binary_tree):
“”"
前序遍历
:param _binary_tree: 二叉树
:type _binary_tree: TreeNode
“”"

if _binary_tree is None:
return
print(_binary_tree.data, end=’’)
pre_order_traverse(_binary_tree.left)
pre_order_traverse(_binary_tree.right)

def in_order_traverse(_binary_tree):
“”"
中序遍历
:param _binary_tree: 二叉树
:type _binary_tree: TreeNode
“”"

if _binary_tree is None:
return
in_order_traverse(_binary_tree.left)
print(_binary_tree.data, end=’’)
in_order_traverse(_binary_tree.right)

def post_order_traverse(_binary_tree):
“”"
后序遍历
:param _binary_tree: 二叉树
:type _binary_tree: TreeNode
“”"

if _binary_tree is None:
return
post_order_traverse(_binary_tree.left)
post_order_traverse(_binary_tree.right)
print(_binary_tree.data, end=’’)

def layer_order_traverse(_layer_nodes):
“”"
按层遍历
:param _layer_nodes: 当前层节点集合
:type _layer_nodes: list
“”"

if _layer_nodes is None or len(_layer_nodes) == 0:
return
_childs = [] # 子集
for _node in _layer_nodes: # 遍历传入的当前层所有节点
print(_node.data, end=’’)
if _node.left:
_childs.append(_node.left)
if _node.right:
_childs.append(_node.right)
layer_order_traverse(_childs)

if name == main:
binary_tree = fixed_tree()
print(‘前序遍历:’, end=’’)
pre_order_traverse(binary_tree)
print()
print(‘中序遍历:’, end=’’)
in_order_traverse(binary_tree)
print()
print(‘后序遍历:’, end=’’)
post_order_traverse(binary_tree)
print()
print(‘按层遍历:’, end=’’)
layer_order_traverse([binary_tree])

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
                                </div>
            <link href="https://csdnimg.cn/release/phoenix/mdeditor/markdown_views-e9f16cbbc2.css" rel="stylesheet">
                </div>
转载:本文链接: https://blog.csdn.net/u013632755/article/details/102763152

前言

二叉树的遍历是指从根节点触发,按照某种次序依次访问二叉树中所有的节点。
由于不同于线性结构,二叉树达到一个节点需要选择两个子节点的先后顺序,所有遍历方式有很多。

二叉树遍历方法

There are many binary tree traversal, so as to traverse way of introduction, we agreed to traverse from left to right.
We need to traverse the tree structure as follows:
Here Insert Picture Description
The following traversal algorithm implemented in Python, Python students will not have to worry about, because the algorithm logic is simple.
We look at the definition of node objects:

class TreeNode:
<span class="token keyword">def</span> <span class="token function">__init__</span><span class="token punctuation">(</span>self<span class="token punctuation">,</span> data<span class="token punctuation">)</span> <span class="token operator">-</span><span class="token operator">&gt;</span> <span class="token boolean">None</span><span class="token punctuation">:</span>
    self<span class="token punctuation">.</span>data <span class="token operator">=</span> data  <span class="token comment"># 数据</span>
    self<span class="token punctuation">.</span>left <span class="token operator">=</span> <span class="token boolean">None</span>  <span class="token comment"># 左子节点</span>
    self<span class="token punctuation">.</span>right <span class="token operator">=</span> <span class="token boolean">None</span>  <span class="token comment"># 右子节点</span>

Guess you like

Origin blog.csdn.net/GUO_z_y/article/details/102779836