2021-06-26 force deduction algorithm problem summary

Posted by MrBillybob on Sun, 23 Jan 2022 13:49:58 +0100

@Binary tree summary

Binary tree phased summary

From today on, I began to record my daily study and life. I didn't blog much before. Although I learned some Markdown grammar, I'm still not very familiar with it. The topics of Li Kou are recorded through pycharm. Later, in this form, I'll record all kinds of learning, do algorithm problems and do the daily work of the project

Traversal of binary tree

Tip: after the article is written, the directory can be generated automatically. Please refer to the help document on the right for how to generate it

preface

Tip: Here you can add the general contents to be recorded in this article:
For example, with the continuous development of artificial intelligence, machine learning technology is becoming more and more important. Many people have started learning machine learning. This paper introduces the basic content of machine learning.

Tip: the following is the main content of this article. The following cases can be used for reference

1, Three traversal methods based on depth first traversal

Definition of binary tree:

The code is as follows (example):

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

1. Preorder traversal (root - > left - > right)

The recursive method is easy to write, but the iterative method can refer to the following ideas, which I think is a better way to understand and remember at present.

Idea:

  • Take advantage of the last in, first out feature of the stack
  • The stack order is left and right
  • The stack order is about the root

The code is as follows (example):

# Recursive mode
	def preorderTraversal1(self, root: TreeNode) -> List[int]:
		# Add node values recursively based on the left and right of the root
		def dfs(root: TreeNode): 
			if not root:
				return []
			res.append(root.val) 
			dfs(root.left)
			dfs(root.right)
		res = []
		dfs(root)
		return res
# Iterative method
    def preorderTraversal2(self, root: TreeNode) -> List[int]:
        if not root: 
            return []
		# Here, the stack is used, using the last in first out feature of the stack
        res, stack = [], [root]
        while stack:
            node = stack.pop()
            if node and type(node) == int: # Find the value of the root and add it
                res.append(node)
                continue
            # Note that the order of addition here is left and right roots
            if node: # Here, as long as the node is not empty, other information will be added
                stack.append(node.right) # Add left child
                stack.append(node.left)  # Add right child
                stack.append(node.val)   # Add value of root
        return res

2. Middle order traversal (left - > root - > right)

The middle order and the rear order are similar. I won't repeat the idea here
The code is as follows (example)

# Recursive mode
	def inorderTraversal1(self, root: TreeNode) -> List[int]:
		def dfs(root: TreeNode): 
			if not root:
				return []
			
			dfs(root.left)
			res.append(root.val) 
			dfs(root.right)
		res = []
		dfs(root)
		return res
# Iterative method
    def inorderTraversal2(self, root: TreeNode) -> List[int]:
        if not root:
            return []
        res, stack = [], [root]
        while stack:
            node = stack.pop()
            if node and type(node) == int:
                res.append(node)
                continue
            if node:
                stack.append(node.right)
                stack.append(node.val)
                stack.append(node.left)
        return res

3. Post order traversal

The code is as follows (example)

# Recursive thinking
	def postorderTraversal1(self, root: TreeNode) -> List[int]:
		def dfs(root: TreeNode): 
			if not root:
				return []
			
			dfs(root.left)
			res.append(root.val) 
			dfs(root.right)
		res = []
		dfs(root)
		return res
#Iterative thinking
    def postorderTraversal(self, root: TreeNode) -> List[int]:
        if not root:
            return []

        res, stack = [], [root]
        while stack:
            node = stack.pop()
            if node and type(node) == int:
                res.append(node)
                continue
            if node:
                stack.append(node.val)
                stack.append(node.right)
                stack.append(node.left)
        return res

The above is the comparison of three binary trees based on depth first traversal. In the following order, I will continue to summarize other knowledge about binary trees

2, Three ways based on breadth first traversal

The code is as follows (example):

from collections import deque
class Solution:
    def levelOrder(self, root: TreeNode) -> List[List[int]]:
        if not root:
            return []
        queue = deque([root])
        res = []
        while queue:
            res1 = []
            for i in range(len(queue)):
                cur = queue.popleft()
                res1.append(cur.val)
                if cur.left:
                    queue.append(cur.left)
                if cur.right:
                    queue.append(cur.right)
            res.append(res1)
        return res

summary

On the traversal of binary tree, that's all for today. Continue to share next time

Topics: Python Algorithm leetcode Programmer Binary tree