遞迴遍歷 (必須掌握)
二叉樹的三種遞迴遍歷掌握其規律後,其實很簡單
題目連結/文章講解/影片講解:https://programmercarl.com/二叉樹的遞迴遍歷.html
注意前 中 後指的是根節點在前、中、後次序進行遍歷。
前序遍歷
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
# 中 左 右
def Traversal(root,res):
if root is None:
return 0
res.append(root.val)
Traversal(root.left,res)
Traversal(root.right,res)
class Solution:
def preorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
res = []
Traversal(root,res)
return res
中序遍歷
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
# 左 中 右
def inorder(root,res):
if root is None:
return 0
inorder(root.left,res)
res.append(root.val)
inorder(root.right,res)
class Solution:
def inorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
res = []
inorder(root,res)
return res
後序遍歷
# 左 右 中
def Traversal(root,res):
if root is None:
return 0
Traversal(root.left,res)
Traversal(root.right,res)
res.append(root.val)
class Solution:
def postorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
res = []
Traversal(root,res)
return res