Python implements binary tree recursive traversal

1. Introduction

1. Full binary tree

Full binary tree: If a binary tree has only nodes with degree 0 and nodes with degree 2, and the nodes with degree 0 are on the same level, then this binary tree is a full binary tree, which can also be said to have a depth of k. A binary tree with 2^k-1 nodes.
binary tree

2. Complete binary tree

The definition of a complete binary tree is as follows: In a complete binary tree, except for the bottom node that may not be filled, the number of nodes in each layer reaches the maximum value, and the nodes in the bottom layer are all concentrated in the leftmost positions of the layer. If the bottom layer is the hth layer, this layer contains 1~ 2^(h-1) nodes, as shown in the figure below: the
binary tree
heap is a complete binary tree, and the sequence relationship between parent and child nodes is guaranteed.

3. Binary search tree

A binary search tree is an ordered tree:

  • If its left subtree is not empty, the values ​​of all nodes on the left subtree are less than the value of its root node;
  • If its right subtree is not empty, the values ​​of all nodes on the right subtree are greater than the value of its root node;
  • Its left and right subtrees are also binary sorted trees

The following two trees are binary search trees:
binary tree

4. Balanced Binary Search Tree

Balanced binary search tree: also known as AVL (Adelson-Velsky and Landis) tree, and has the following properties: it is an empty tree or the absolute value of the height difference between its left and right subtrees does not exceed 1, and the left and right Both subtrees are a balanced binary tree .
As shown in the figure:
binary search tree
the last one is not a balanced binary tree, because the absolute value of the height difference between its left and right subtrees exceeds 1.

Two. Binary tree front, middle and back order traversal

Looking at the order of the intermediate nodes below, you can find that the order of the intermediate nodes is the so-called traversal method:

  • Preorder traversal: middle left
  • Inorder traversal: left center right
  • Post-order traversal: left, right, middle

For example, as shown in the figure below:
binary tree

3. Binary tree definition

Binary tree is a basic data structure. Binary tree has two storage methods, sequential storage and chain storage. Sequential storage uses an array to store, and linked storage uses a linked list to store. Compared with the linked list binary tree node, there is one more pointer, and there are two pointers, pointing to the left and right children.

1. Chain storage

Linked storage uses pointers to connect nodes distributed at various addresses in series. Linked storage is shown in the figure:
binary tree

Define the root node code as follows:

class TreeNode:
    def __init__(self, value):
        self.value = value
        self.left = None
        self.right = None

2. Sequential storage

Use arrays to store binary trees, and the sequential storage method is shown in the figure:
insert image description here

How to use array to store binary tree traversal?

If the array subscript of the parent node is i, then its left child is i * 2 + 1, and its right child is i * 2 + 2.

4. Binary tree recursive traversal

Introduce the three elements of a recursive algorithm. Every time you write recursion, write according to these three elements, which can ensure that you can write the correct recursive algorithm:

  1. Determine the parameters and return values ​​of the recursive function: Determine which parameters need to be processed during the recursion process, then add this parameter to the recursive function, and also specify what the return value of each recursion is to determine the return type of the recursive function .

  2. Determine the termination condition: After writing the recursive algorithm, when it is running, it often encounters a stack overflow error, that is, the termination condition is not written or the termination condition is written incorrectly. The operating system also uses a stack structure to save the information of each layer of recursion , if the recursion is not terminated, the operating system's memory stack will inevitably overflow.

  3. Determine the logic of single-level recursion: Determine the information that needs to be processed for each level of recursion. Here, the process of calling itself repeatedly to achieve recursion will also be repeated.

1. Preorder traversal implementation

from typing import List

###树节点数据结构定义
class TreeNode:
    def __init__(self, val):
        self.val = val
        self.left = None
        self.right = None
        
# 前序遍历-递归-LC144_二叉树的前序遍历
class Solution:
    def preorderTraversal(self, root: TreeNode) -> List[int]:
        # 保存结果
        result = []
        
        def traversal(root: TreeNode):
            if root == None:
                return
            result.append(root.val) # 前序
            traversal(root.left)    # 左
            traversal(root.right)   # 右

        traversal(root)
        return result

2. Inorder traversal implementation

from typing import List

###树节点数据结构定义
class TreeNode:
    def __init__(self, val):
        self.val = val
        self.left = None
        self.right = None

# 中序遍历-递归-LC94_二叉树的中序遍历
class Solution:
    def inorderTraversal(self, root: TreeNode) -> List[int]:
        result = []

        def traversal(root: TreeNode):
            if root == None:
                return
            traversal(root.left)    # 左
            result.append(root.val) # 中序
            traversal(root.right)   # 右

        traversal(root)
        return result

3. Post-order traversal implementation

from typing import List

###树节点数据结构定义
class TreeNode:
    def __init__(self, val):
        self.val = val
        self.left = None
        self.right = None

# 后序遍历-递归-LC145_二叉树的后序遍历
class Solution:
    def postorderTraversal(self, root: TreeNode) -> List[int]:
        result = []

        def traversal(root: TreeNode):
            if root == None:
                return
            traversal(root.left)    # 左
            traversal(root.right)   # 右
            result.append(root.val) # 后序

        traversal(root)
        return result

5. Binary tree iterative traversal

  1. Next section: Python implements binary tree iterative traversal

Guess you like

Origin blog.csdn.net/flyingluohaipeng/article/details/129748182