Get the App
SLTechnology News&Howtos  ›  Development  › 

How to use Python recursion to realize preorder, middle order and post order traversal of binary tree

Shulou Source: shulou.com Published: 2022-06-01 06:59:48 10月03日 Update

Today, I would like to share with you how to use Python recursion to achieve binary tree preorder, middle order, and post-order traversal of the relevant knowledge points, detailed content, clear logic, I believe that most people still know too much about this knowledge, so share this article for your reference, hope you can get something after reading this article, let's take a look at it.

Memory points:

Preface: VLR

Middle order: LVR

Post order: LRV

For example:

A binary tree is shown below:

Then its pre-order, middle-order, and post-order traversal process is shown in the following figure:

1. Preorder traverses class Solution: def preorderTraversal (self, root: TreeNode): def preorder (root: TreeNode): if not root: return res.append (root.val) preorder (root.left) preorder (root.right) res = [] preorder (root) return res2. Traverse class Solution: def inorderTraversal (self, root: TreeNode): def inorder (root: TreeNode): if not root: return inorder (root.left) res.append (root.val) inorder (root.right) res = [] inorder (root) return res3. Traverse class Solution: def postorderTraversal (self, root: TreeNode): def postorder (root: TreeNode): if not root: return postorder (root.left) res.append (root.val) postorder (root.right) res = [] postorder (root) return res4. Test class TreeNode: def _ init__ (self, val=0, left=None, right=None): self.val = val self.left = left self.right = right# create a binary tree def createTree (root,list_n) with list recursion I): if i List [int]: def seq (root): if not root: return res.append (root.val) for child in root.children: seq (child) res = [] seq (root) return resN fork tree traversing "" # Definition for a " Node.class Node: def _ _ init__ (self Val=None, children=None): self.val = val self.children = children "" class Solution: def postorder (self Root: 'Node')-> List [int]: def seq (root): if not root: return for child in root.children: seq (child) res.append (root.val) res = [] seq (root) return res above is "how to use Python recursion to achieve binary tree preorder, intermediate order Traversing all the contents of this article in the later order Thank you for reading! I believe you will gain a lot after reading this article. The editor will update different knowledge for you every day. If you want to learn more knowledge, please pay attention to the industry information channel.

Tags: Knowledge articles recursion content different very big most that is more processes knowledge points results industry memory information information channels logic facets channels Tiandu Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno NVidia OPPO Reno macOS Xiaomi MySQL