Python 遞歸式實現二叉樹前序,中序,後序遍歷
記憶點:
- 前序:VLR
- 中序:LVR
- 後序:LRV
舉例:
一顆二叉樹如下圖所示:
則它的前序、中序、後序遍歷流程如下圖所示:
1.前序遍歷
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 res
2.中序遍歷
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 res
3.後序遍歷
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 res
4.測試
class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right # 用列表遞歸創建二叉樹 def createTree(root,list_n,i): if i <len(list_n): if list_n[i] == 'null': return None else: root = TreeNode(val = list_n[i]) root.left = createTree(root.left,list_n,2*i+1) root.right = createTree(root.right,list_n,2*i+2) return root return root 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 res 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 res def postorderTraversal(self, root: TreeNode): # 後序 def postorder(root: TreeNode): if not root: return postorder(root.left) postorder(root.right) res.append(root.val) res = [] postorder(root) return res if __name__ == "__main__": root = TreeNode() list_n = [1,2,3,4,5,6,7,8,'null',9,10] root = createTree(root,list_n,0) s = Solution() res_pre = s.preorderTraversal(root) res_in = s.inorderTraversal(root) res_post = s.postorderTraversal(root) print(res_pre) print(res_in) print(res_post)
5.結果
6.補充
6.1N叉樹前序遍歷
""" # 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 res.append(root.val) for child in root.children: seq(child) res = [] seq(root) return res N叉樹後序遍歷 """ # 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
到此這篇關於Python 遞歸式實現二叉樹前序,中序,後序遍歷的文章就介紹到這瞭,更多相關二叉樹前序,中序,後序遍歷內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!
推薦閱讀:
- C++實現LeetCode(105.由先序和中序遍歷建立二叉樹)
- C語言植物大戰數據結構二叉樹遞歸
- C++實現LeetCode(106.由中序和後序遍歷建立二叉樹)
- Java數據結構之樹和二叉樹的相關資料
- C++實現LeetCode(98.驗證二叉搜索樹)