From a3dee1e821cd6fac9818bb64e896c97c72a82ead Mon Sep 17 00:00:00 2001 From: inter Date: Mon, 8 Sep 2025 16:35:56 +0800 Subject: [PATCH] Add File --- backend/common/utils/tree_utils.py | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 backend/common/utils/tree_utils.py diff --git a/backend/common/utils/tree_utils.py b/backend/common/utils/tree_utils.py new file mode 100644 index 0000000..8398d65 --- /dev/null +++ b/backend/common/utils/tree_utils.py @@ -0,0 +1,22 @@ +from typing import List, Optional, Dict, TypeVar, Protocol, Any +from pydantic import BaseModel + + +class ITreeNode(Protocol): + id: Optional[str] + pid: Optional[str] + children: List['ITreeNode'] + +T = TypeVar('T', bound=ITreeNode) + +def build_tree_generic(nodes: List[T], root_pid: Any = None) -> List[T]: + node_dict: Dict[str, T] = {node.id: node for node in nodes if node.id is not None} + tree: List[T] = [] + + for node in nodes: + if node.pid == root_pid: + tree.append(node) + elif node.pid in node_dict: + node_dict[node.pid].children.append(node) + + return tree \ No newline at end of file