JavaScript 递归创建多叉树

(一) 创建一个 Node 类,生成树的结点。

export default class Node {
  name = '';

  constructor(name) {
    this.name = name;
  }

  children = [];

  add(children) {
    for (let i = 0; i < children.length; i += 1) {
      const child = children[i];

      if (child === null) {
        return this;
      }

      if (child.parent != null) {
        children[i].parent.remove(child);
      }

      child.parent = this;
      this.children.push(child);
    }

    return null;
  }

  remove(child) {
    const index = this.children.indexOf(child);

    if (index > -1) {
      child.parent = undefined;

      this.children.slice(index, 1);

      return child;
    }

    return null;
  }
}

(二) 根据测试数据,递归生成多叉树。

const testNode = {
  n0: {
    children: ['n1', 'n2', 'n5'],
  },
  n1: {
    children: ['n3', 'n8', 'n7'],
  },
  n2: {
    children: [],
    meshes: ['m1'],
  },
  n3: {
    children: ['n4'],
  },
  n4: {
    children: [],
    meshes: ['m0'],
  },
  n5: {
    children: [],
    meshes: ['m1'],
  },

  n6: {
    children: [],
  },
  n7: {
    children: ['n10'],
  },
  n8: {
    children: [],
    meshes: ['m2'],
  },
  n9: {
    children: [],
    meshes: ['m3'],
  },
  n10: {
    children: [],
    meshes: ['m4'],

  },
};

/**
 * meshes 测试数据
 */
const meshesObj = {
  children: [
    {
      aa: 'bb',
    },
    {
      aa: 'bb',
    },
    {
      aa: 'bb',
    },
    {
      aa: 'bb',
    },
    {
      aa: 'bb',
    },
    {
      aa: 'bb',
    },
  ],
};

/**
 * 递归遍历生成多叉树
 *
 * @param {*} node - nodes 列表中的一个 node
 * @param {*} parentNode - node 的父结点,为 Node 对象。
 */
const traverseNodes = (node, parentNode) => {
  if (node.children.length > 0) {
    const { length } = node.children;

    for (let i = 0; i < length; i += 1) {
      const nodeName = node.children[i];
      const childNode = new Node(nodeName);
      parentNode.add([childNode]);
      const newChildren = testNode[nodeName];
      traverseNodes(newChildren, childNode);
    }
  } else {
    const { meshes } = node;
    const meshesLsit = [];

    for (let i = 0; i < meshes.length; i += 1) {
      const meshName = meshes[i];
      for (let j = 0; j < meshesObj.children.length; j += 1) {
        const mesh = meshesObj.children[j];
        if (mesh.name === meshName) {
          meshesLsit.push(mesh);
        }
      }
    }

    parentNode.add(meshesLsit);
  }
};

// 多叉树的根结点
const root = new Node('n0');

traverseNodes(testNode.n0, root);

console.log(root);

你可能感兴趣的:(JavaScript 递归创建多叉树)