程式碼隨想錄演算法訓練營第14|
二叉樹理論
https://programmercarl.com/二叉樹理論基礎.html
二叉樹遞迴遍歷
https://programmercarl.com/二叉樹的遞迴遍歷.html
二叉樹統一迭代
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
class Solution:
def preorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
res = []
if not root:
return res
else:
right = self.preorderTraversal(root.right)
left = self.preorderTraversal(root.left)
return [root.val]+left+right
二叉樹統一迭代
重點
- 棧儲存
- node後接None
- 反向push
題解
class Solution:
def preorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
st = []
res = []
if root:
st.append(root)
while st:
node = st.pop()
if node:
if node.right:
st.append(node.right)
if node.left:
st.append(node.left)
st.append(node)
st.append(None)
else:
node = st.pop()
res.append(node.val)
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
class Solution:
def levelOrder(self, root: Optional[TreeNode]) -> List[List[int]]:
if not root:
return []
queue = collections.deque([root])
res = []
while queue:
level = []
for _ in range(len(queue)):
node = queue.popleft()
level.append(node.val)
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
res.append(level)
return res