hello-algo/codes/python/modules/binary_tree.py

73 lines
1.8 KiB
Python
Raw Normal View History

"""
File: binary_tree.py
Created Time: 2021-12-11
Author: Krahets (krahets@163.com)
"""
from collections import deque
2023-04-09 05:05:35 +08:00
class TreeNode:
2023-04-09 05:05:35 +08:00
"""Definition for a binary tree node"""
def __init__(self, val: int = 0):
2023-04-09 05:05:35 +08:00
self.val: int = val # 节点值
self.height: int = 0 # 节点高度
self.left: TreeNode | None = None # 左子节点引用
2023-04-09 05:05:35 +08:00
self.right: TreeNode | None = None # 右子节点引用
2022-12-27 18:34:12 +08:00
def list_to_tree(arr: list[int]) -> TreeNode | None:
2023-04-09 05:05:35 +08:00
"""Generate a binary tree with a list"""
if not arr:
2022-12-02 00:53:19 +08:00
return None
2023-04-09 05:05:35 +08:00
i = 0
root = TreeNode(arr[0])
queue: deque[TreeNode] = deque([root])
while queue:
node: TreeNode = queue.popleft()
i += 1
2023-04-09 05:05:35 +08:00
if i >= len(arr):
break
if arr[i] != None:
node.left = TreeNode(arr[i])
queue.append(node.left)
i += 1
2023-04-09 05:05:35 +08:00
if i >= len(arr):
break
if arr[i] != None:
node.right = TreeNode(arr[i])
queue.append(node.right)
2023-04-09 05:05:35 +08:00
return root
2023-04-09 05:05:35 +08:00
def tree_to_list(root: TreeNode | None) -> list[int]:
2023-04-09 05:05:35 +08:00
"""Serialize a tree into an array"""
if not root:
return []
queue: deque[TreeNode] = deque()
queue.append(root)
res: list[int] = []
while queue:
node: TreeNode | None = queue.popleft()
if node:
res.append(node.val)
queue.append(node.left)
queue.append(node.right)
2023-04-09 05:05:35 +08:00
else:
res.append(None)
return res
2023-04-09 05:05:35 +08:00
def get_tree_node(root: TreeNode | None, val: int) -> TreeNode | None:
2023-04-09 05:05:35 +08:00
"""Get a tree node with specific value in a binary tree"""
if not root:
return
if root.val == val:
return root
left: TreeNode | None = get_tree_node(root.left, val)
right: TreeNode | None = get_tree_node(root.right, val)
return left if left else right