常用树算法

2021-09-22  本文已影响0人  千茉紫依
  1. B树中找一个节点的父节点
findParentById = (json, id) => {
    let parentNode = null;
    let node = null;
    const getNode = (json, id) => {
      //1.第一层 root 深度遍历整个JSON
      for (let i = 0; i < json.length; i++) {
        if (node) {
          break;
        }
        let obj = json[i];
        //没有就下一个
        if (!obj || !obj.id) {
          continue;
        }
        //2.有节点就开始找,一直递归下去
        if (obj.id == id) {
          //找到了与text匹配的节点,结束递归
          node = obj;
          break;
        } else {
          //3.如果有子节点就开始找
          if (obj.children && obj.children.length != 0) {
            //4.递归前,记录当前节点,作为parent 父亲
            parentNode = obj;
            //递归往下找
            getNode(obj.children, id);
          } else {
            //跳出当前递归,返回上层递归
            continue;
          }
        }
      }
      //5.如果木有找到父节点,置为null,因为没有父亲  
      if (!node) {
        parentNode = null;
      }
      //6.返回结果obj
      return {
        parentNode: parentNode,
        node: node
      };
    }
    let result = [];
    let getResult = function (json, id) {
      node = null;
      parentNode = null;
      let obj = getNode(json, id);
      //判断是否闭包
      if (obj.parentNode) {
        //有父节点
        //获取父节点text继续查祖节点
        getResult(json, obj.parentNode.id);
        result.push(obj.parentNode.id);
      }
      return result;
    }
    getResult(json, id);
    //最后将查询push到result中
    result.push(id);
    console.log(result)
    return result
  }
  1. 树结构所有子节点属性值修改
const mapTree = org => {
    const haveChildren = Array.isArray(org.children) && org.children.length > 0;
    return {
         id : org.id,
         text: org.text,
         children:haveChildren ? org.children.map(i => mapTree(i)) : [],
     }
}
上一篇 下一篇

猜你喜欢

热点阅读