Rewrite the tree serialization and deserialization methods. Add applications of array and linked list.pull/601/head^2
parent
c68f18e480
commit
4e13755023
@ -0,0 +1,137 @@
|
||||
/**
|
||||
* File: array_binary_tree.cpp
|
||||
* Created Time: 2023-07-19
|
||||
* Author: Krahets (krahets@163.com)
|
||||
*/
|
||||
|
||||
#include "../utils/common.hpp"
|
||||
|
||||
/* 数组表示下的二叉树类 */
|
||||
class ArrayBinaryTree {
|
||||
public:
|
||||
/* 构造方法 */
|
||||
ArrayBinaryTree(vector<int> arr) {
|
||||
tree = arr;
|
||||
}
|
||||
|
||||
/* 节点数量 */
|
||||
int size() {
|
||||
return tree.size();
|
||||
}
|
||||
|
||||
/* 获取索引为 i 节点的值 */
|
||||
int val(int i) {
|
||||
// 若索引越界,则返回 INT_MAX ,代表空位
|
||||
if (i < 0 || i >= size())
|
||||
return INT_MAX;
|
||||
return tree[i];
|
||||
}
|
||||
|
||||
/* 获取索引为 i 节点的左子节点的索引 */
|
||||
int left(int i) {
|
||||
return 2 * i + 1;
|
||||
}
|
||||
|
||||
/* 获取索引为 i 节点的右子节点的索引 */
|
||||
int right(int i) {
|
||||
return 2 * i + 2;
|
||||
}
|
||||
|
||||
/* 获取索引为 i 节点的父节点的索引 */
|
||||
int parent(int i) {
|
||||
return (i - 1) / 2;
|
||||
}
|
||||
|
||||
/* 层序遍历 */
|
||||
vector<int> levelOrder() {
|
||||
vector<int> res;
|
||||
// 直接遍历数组
|
||||
for (int i = 0; i < size(); i++) {
|
||||
if (val(i) != INT_MAX)
|
||||
res.push_back(val(i));
|
||||
}
|
||||
return res;
|
||||
}
|
||||
|
||||
/* 前序遍历 */
|
||||
vector<int> preOrder() {
|
||||
vector<int> res;
|
||||
dfs(0, "pre", res);
|
||||
return res;
|
||||
}
|
||||
|
||||
/* 中序遍历 */
|
||||
vector<int> inOrder() {
|
||||
vector<int> res;
|
||||
dfs(0, "in", res);
|
||||
return res;
|
||||
}
|
||||
|
||||
/* 后序遍历 */
|
||||
vector<int> postOrder() {
|
||||
vector<int> res;
|
||||
dfs(0, "post", res);
|
||||
return res;
|
||||
}
|
||||
|
||||
private:
|
||||
vector<int> tree;
|
||||
|
||||
/* 深度优先遍历 */
|
||||
void dfs(int i, string order, vector<int> &res) {
|
||||
// 若为空位,则返回
|
||||
if (val(i) == INT_MAX)
|
||||
return;
|
||||
// 前序遍历
|
||||
if (order == "pre")
|
||||
res.push_back(val(i));
|
||||
dfs(left(i), order, res);
|
||||
// 中序遍历
|
||||
if (order == "in")
|
||||
res.push_back(val(i));
|
||||
dfs(right(i), order, res);
|
||||
// 后序遍历
|
||||
if (order == "post")
|
||||
res.push_back(val(i));
|
||||
}
|
||||
};
|
||||
|
||||
/* Driver Code */
|
||||
int main() {
|
||||
// 初始化二叉树
|
||||
// 使用 INT_MAX 代表空位 nullptr
|
||||
vector<int> arr = {1, 2, 3, 4, INT_MAX, 6, 7, 8, 9, INT_MAX, INT_MAX, 12, INT_MAX, INT_MAX, 15};
|
||||
TreeNode *root = vectorToTree(arr);
|
||||
cout << "\n初始化二叉树\n";
|
||||
cout << "二叉树的数组表示:\n";
|
||||
printVector(arr);
|
||||
cout << "二叉树的链表表示:\n";
|
||||
printTree(root);
|
||||
|
||||
// 数组表示下的二叉树类
|
||||
ArrayBinaryTree abt(arr);
|
||||
|
||||
// 访问节点
|
||||
int i = 1;
|
||||
int l = abt.left(i), r = abt.right(i), p = abt.parent(i);
|
||||
cout << "\n当前节点的索引为 " << i << ",值为 " << abt.val(i) << "\n";
|
||||
cout << "其左子节点的索引为 " << l << ",值为 " << (l != INT_MAX ? to_string(abt.val(l)) : "None") << "\n";
|
||||
cout << "其右子节点的索引为 " << r << ",值为 " << (r != INT_MAX ? to_string(abt.val(r)) : "None") << "\n";
|
||||
cout << "其父节点的索引为 " << p << ",值为 " << (p != INT_MAX ? to_string(abt.val(p)) : "None") << "\n";
|
||||
|
||||
// 遍历树
|
||||
vector<int> res = abt.levelOrder();
|
||||
cout << "\n层序遍历为: ";
|
||||
printVector(res);
|
||||
res = abt.preOrder();
|
||||
cout << "前序遍历为: ";
|
||||
printVector(res);
|
||||
res = abt.inOrder();
|
||||
cout << "中序遍历为: ";
|
||||
printVector(res);
|
||||
res = abt.postOrder();
|
||||
cout << "后序遍历为: ";
|
||||
printVector(res);
|
||||
|
||||
return 0;
|
||||
}
|
@ -0,0 +1,118 @@
|
||||
"""
|
||||
File: array_binary_tree.py
|
||||
Created Time: 2023-07-19
|
||||
Author: Krahets (krahets@163.com)
|
||||
"""
|
||||
|
||||
import sys, os.path as osp
|
||||
|
||||
sys.path.append(osp.dirname(osp.dirname(osp.abspath(__file__))))
|
||||
from modules import *
|
||||
|
||||
|
||||
class ArrayBinaryTree:
|
||||
"""数组表示下的二叉树类"""
|
||||
|
||||
def __init__(self, arr: list[int | None]):
|
||||
"""构造方法"""
|
||||
self.__tree = list(arr)
|
||||
|
||||
def size(self):
|
||||
"""节点数量"""
|
||||
return len(self.__tree)
|
||||
|
||||
def val(self, i: int) -> int:
|
||||
"""获取索引为 i 节点的值"""
|
||||
# 若索引越界,则返回 None ,代表空位
|
||||
if i < 0 or i >= self.size():
|
||||
return None
|
||||
return self.__tree[i]
|
||||
|
||||
def left(self, i: int) -> int | None:
|
||||
"""获取索引为 i 节点的左子节点的索引"""
|
||||
return 2 * i + 1
|
||||
|
||||
def right(self, i: int) -> int | None:
|
||||
"""获取索引为 i 节点的右子节点的索引"""
|
||||
return 2 * i + 2
|
||||
|
||||
def parent(self, i: int) -> int | None:
|
||||
"""获取索引为 i 节点的父节点的索引"""
|
||||
return (i - 1) // 2
|
||||
|
||||
def level_order(self) -> list[int]:
|
||||
"""层序遍历"""
|
||||
self.res = []
|
||||
# 直接遍历数组
|
||||
for i in range(self.size()):
|
||||
if self.val(i) is not None:
|
||||
self.res.append(self.val(i))
|
||||
return self.res
|
||||
|
||||
def __dfs(self, i: int, order: str):
|
||||
"""深度优先遍历"""
|
||||
if self.val(i) is None:
|
||||
return
|
||||
# 前序遍历
|
||||
if order == "pre":
|
||||
self.res.append(self.val(i))
|
||||
self.__dfs(self.left(i), order)
|
||||
# 中序遍历
|
||||
if order == "in":
|
||||
self.res.append(self.val(i))
|
||||
self.__dfs(self.right(i), order)
|
||||
# 后序遍历
|
||||
if order == "post":
|
||||
self.res.append(self.val(i))
|
||||
|
||||
def pre_order(self) -> list[int]:
|
||||
"""前序遍历"""
|
||||
self.res = []
|
||||
self.__dfs(0, order="pre")
|
||||
return self.res
|
||||
|
||||
def in_order(self) -> list[int]:
|
||||
"""中序遍历"""
|
||||
self.res = []
|
||||
self.__dfs(0, order="in")
|
||||
return self.res
|
||||
|
||||
def post_order(self) -> list[int]:
|
||||
"""后序遍历"""
|
||||
self.res = []
|
||||
self.__dfs(0, order="post")
|
||||
return self.res
|
||||
|
||||
|
||||
"""Driver Code"""
|
||||
if __name__ == "__main__":
|
||||
# 初始化二叉树
|
||||
# 这里借助了一个从数组直接生成二叉树的函数
|
||||
arr = [1, 2, 3, 4, None, 6, 7, 8, 9, None, None, 12, None, None, 15]
|
||||
root = list_to_tree(arr)
|
||||
print("\n初始化二叉树\n")
|
||||
print(f"二叉树的数组表示:")
|
||||
print(arr)
|
||||
print(f"二叉树的链表表示:")
|
||||
print_tree(root)
|
||||
|
||||
# 数组表示下的二叉树类
|
||||
abt = ArrayBinaryTree(arr)
|
||||
|
||||
# 访问节点
|
||||
i = 1
|
||||
l, r, p = abt.left(i), abt.right(i), abt.parent(i)
|
||||
print(f"\n当前节点的索引为 {i} ,值为 {abt.val(i)}")
|
||||
print(f"其左子节点的索引为 {l} ,值为 {abt.val(l)}")
|
||||
print(f"其右子节点的索引为 {r} ,值为 {abt.val(r)}")
|
||||
print(f"其父节点的索引为 {p} ,值为 {abt.val(p)}")
|
||||
|
||||
# 遍历树
|
||||
res = abt.level_order()
|
||||
print("\n层序遍历为:", res)
|
||||
res = abt.pre_order()
|
||||
print("前序遍历为:", res)
|
||||
res = abt.in_order()
|
||||
print("中序遍历为:", res)
|
||||
res = abt.post_order()
|
||||
print("后序遍历为:", res)
|
@ -1,72 +0,0 @@
|
||||
"""
|
||||
File: binary_tree.py
|
||||
Created Time: 2021-12-11
|
||||
Author: Krahets (krahets@163.com)
|
||||
"""
|
||||
|
||||
from collections import deque
|
||||
|
||||
|
||||
class TreeNode:
|
||||
"""Definition for a binary tree node"""
|
||||
|
||||
def __init__(self, val: int = 0):
|
||||
self.val: int = val # 节点值
|
||||
self.height: int = 0 # 节点高度
|
||||
self.left: TreeNode | None = None # 左子节点引用
|
||||
self.right: TreeNode | None = None # 右子节点引用
|
||||
|
||||
|
||||
def list_to_tree(arr: list[int]) -> TreeNode | None:
|
||||
"""Generate a binary tree with a list"""
|
||||
if not arr:
|
||||
return None
|
||||
|
||||
i = 0
|
||||
root = TreeNode(arr[0])
|
||||
queue: deque[TreeNode] = deque([root])
|
||||
while queue:
|
||||
node: TreeNode = queue.popleft()
|
||||
i += 1
|
||||
if i >= len(arr):
|
||||
break
|
||||
if arr[i] != None:
|
||||
node.left = TreeNode(arr[i])
|
||||
queue.append(node.left)
|
||||
i += 1
|
||||
if i >= len(arr):
|
||||
break
|
||||
if arr[i] != None:
|
||||
node.right = TreeNode(arr[i])
|
||||
queue.append(node.right)
|
||||
|
||||
return root
|
||||
|
||||
|
||||
def tree_to_list(root: TreeNode | None) -> list[int]:
|
||||
"""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)
|
||||
else:
|
||||
res.append(None)
|
||||
return res
|
||||
|
||||
|
||||
def get_tree_node(root: TreeNode | None, val: int) -> TreeNode | None:
|
||||
"""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
|
@ -1,5 +1,5 @@
|
||||
"""
|
||||
File: linked_list.py
|
||||
File: list_node.py
|
||||
Created Time: 2021-12-11
|
||||
Author: Krahets (krahets@163.com)
|
||||
"""
|
Loading…
Reference in new issue