MST
星途 面试题库

面试题:TypeScript递归类型构建简单树形结构

请使用TypeScript递归类型构建一个简单的树形数据结构,树节点包含id(唯一标识,数字类型)、name(名称,字符串类型)和children(子节点数组,类型为当前树节点类型)。并编写一个函数,接收树的根节点,返回树中所有节点的id组成的数组。
28.1万 热度难度
前端开发TypeScript

知识考点

AI 面试

面试题答案

一键面试
// 定义树形数据结构
type TreeNode = {
    id: number;
    name: string;
    children?: TreeNode[];
};

// 构建树
const tree: TreeNode = {
    id: 1,
    name: 'root',
    children: [
        {
            id: 2,
            name: 'child1',
            children: [
                {
                    id: 3,
                    name: 'grandchild1'
                }
            ]
        },
        {
            id: 4,
            name: 'child2'
        }
    ]
};

// 获取所有节点id的函数
function getAllIds(node: TreeNode): number[] {
    const ids: number[] = [node.id];
    if (node.children) {
        for (const child of node.children) {
            ids.push(...getAllIds(child));
        }
    }
    return ids;
}

// 测试
console.log(getAllIds(tree));