Binary tree: depth-first traversal and breadth-first traversal (and its Python implementation)

Binary tree: depth-first traversal and breadth-first traversal (and its Python implementation)

This question records the characteristics of depth-first traversal algorithm and breadth-first traversal algorithm of binary tree and its python implementation.

1 Depth-first traversal

Depth-first traversal algorithms include pre-order traversal, in-order traversal, and post-order traversal.

1.1 Depth-first traversal order

We illustrate the depth-first traversal order based on the binary tree with only 3 nodes in the figure below.
(each node is marked with a serial number)
3_node

  1. Preorder traversal: 0→1→2
  2. Inorder traversal: 1→0→2
  3. Post-order traversal: 1→2→0

Note that the main difference is the position of node 0 in the sorting, and the relative position of node 1 and node 2 is unchanged (1 is in front and 2 is in the back).

In general, a binary tree is shown in the figure below:
(each node is marked with a serial number)
insert image description here
Take pre-order traversal as an example:
we first look at it from the top, and regard the nodes contained in the left subtree of node 0 as a whole (1, 3, 4, 7, 8, 9) as a whole, which is recorded as whole 1;

  • 0 → whole 1 → whole 2

But overall 1 also contains several nodes, so continue to analyze the nodes in overall 1.
Similarly, when analyzed from top to bottom, the left subtree of node 1 is a whole (3, 7, 8), which is recorded as whole 3; the right subtree is a whole (4, 9), which is recorded as whole 4; therefore, the preorder traversal order in whole 1 is:

  • 1 → whole 3 → whole 4

Similarly, the whole 3 contains several nodes, and it is necessary to continue to analyze the whole 3 (3, 7, 8).
At this time, we found that the left subtree of node 3 has only one node 7, and the right subtree has only one node 8, so the preorder traversal order of the whole 3 is:

  • 3 → 7 → 8

So, according to this method, we can derive the preorder traversal order of the entire binary tree:

  • 0 → 1 → 3 → 7 → 8 → 4 → 9 → 2 → 5 → 6

In the same way, we can deduce the traversal order of the other two depth-first traversals:

  1. Preorder traversal: 0 → 1 → 3 → 7 → 8 → 4 → 9 → 2 → 5 → 6
  2. Inorder traversal: 7 → 3 → 8 → 1 → 9 → 4 → 0 → 5 → 2 → 6
  3. Postorder traversal: 7 → 8 → 3 → 9 → 4 → 1 → 5 → 6 → 2 → 0

1.2 Depth-first traversal Python implementation

According to the above description of the traversal process, we can see that this is actually a recursive process, so the three depth-first traversals can be easily implemented using recursion.

First define the class of nodes and trees and define the method of adding nodes, and then define the methods of pre-order traversal, in-order traversal and post-order traversal in the binary tree class.

# 节点类
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)
        cur_list = [self.root]
        if self.root is None:
            self.root = node
            return
        while True: 
            cur_node = cur_list.pop(0)
            if cur_node.lchild is None:
                cur_node.lchild = node
                return
            else:
                cur_list.append(cur_node.lchild)
            if cur_node.rchild is None:
                cur_node.rchild = node
                return
            else:
                cur_list.append(cur_node.rchild)
    # 先序遍历方法
    def preorder(self, cur_node):
        if cur_node is None:
            return
        print(cur_node.elem, end = " ")
        self.preorder(cur_node.lchild)
        self.preorder(cur_node.rchild)
    # 中序遍历方法
    def inorder(self, cur_node):
        if cur_node is None:
            return
        self.inorder(cur_node.lchild)
        print(cur_node.elem, end = " ")
        self.inorder(cur_node.rchild)
    # 后序遍历方法
    def postorder(self, cur_node):
        if cur_node is None:
            return
        self.postorder(cur_node.lchild)
        self.postorder(cur_node.rchild)
        print(cur_node.elem, end = " ")

test:

tree = Tree()
for i in range(10)
    tree.add(i)
tree.preorder(tree.root)
print(" ")
tree.inorder(tree.root)
print(" ")
tree.postorder(tree.root)

result:

0 1 3 7 8 4 9 2 5 6  
7 3 8 1 9 4 0 5 2 6
7 8 3 9 4 1 5 6 2 0

2 Breadth-first traversal

2.1 Breadth-first traversal order

The traversal order of breadth-first traversal is very simple:
from top to bottom, from left to right. That is to say, the nodes of the same layer are traversed from left to right and then go to the next layer until an empty node is reached.
insert image description here
So for the binary tree shown in the figure:

  • Breadth-first traversal: 0 → 1 → 2 → 3 → 4 → 5 → 6 → 7 → 8 → 9

2.2 Breadth-first traversal Python implementation

Breadth-first traversal can be implemented through loops.
Add the breadth_order method to the binary tree class (Tree) in the preceding code:

    def breadth_order(self):
        queue = [self.root]
        if self.root is None:
            print("No node inside the tree.")
            return
        while queue:
            cur_node = queue.pop(0)
            print(cur_node.elem, end = " ")
            if cur_node.lchild is not None:
                queue.append(cur_node.lchild)
            if cur_node.rchild is not None:
                queue.append(cur_node.rchild)

test:

tree = Tree()
for i in range(10)
    tree.add(i)
tree.breadth_order()

result:

0 1 2 3 4 5 6 7 8 9

Guess you like

Origin blog.csdn.net/weixin_41670608/article/details/115032156