zoukankan      html  css  js  c++  java
  • js中树结构根据条件查找节点返回节点路径的一些思路

      今天在项目中遇到一个问题,需要根据数据库中记录的树结构节点id获取该记录所在目录节点的路径。

      大致想法,首先定义变量保存当前路径,然后递归遍历该树节点,在遍历的过程中将遍历到的节点加入到当前路径中,找到该节点后终止递归,最后返回路径即可。

      问题,怎样保存当前判断节点的路径以及未找到节点时对路径的处理方法。

      现附上代码:

    var getPathById = function (id, catalog, callback) {
    
        //定义变量保存当前结果路径
        var temppath = "";
        try {
            function getNodePath(node) {
                temppath += (node.name + "\");
    
                //找到符合条件的节点,通过throw终止掉递归
                if (node.id == parseInt(cataid)) {
                    throw ("GOT IT!");
                }
                if (node.children && node.children.length > 0) {
                    for (var i = 0; i < node.children.length; i++) {
                        getNodePath(node.children[i]);
                    }
    
                    //当前节点的子节点遍历完依旧没找到,则删除路径中的该节点
                    temppath = temppath.substring(0, temppath.length - 1);
                    temppath = temppath.substring(0, temppath.lastIndexOf("\")) + "\";
                }
                else {
    
                    //找到叶子节点时,删除路径当中的该叶子节点
                    temppath = temppath.substring(0, temppath.length - 1);
                    temppath = temppath.substring(0, temppath.lastIndexOf("\")) + "\";
                }
            }
            getNodePath(catalog);
        }
        catch (e) {
            callback(temppath);
        }
    };
    

      改进,上面的代码是将路径保存在字符串中,最终直接使用即可,更好的方法是保存在数组中。

      改进代码:

    var getPathById = function (id, catalog, callback) {
    
        //定义变量保存当前结果路径
        var temppath = [];
        try {
            function getNodePath(node) {
                temppath.push(node.name);
    
                //找到符合条件的节点,通过throw终止掉递归
                if (node.id == parseInt(cataid)) {
                    throw ("GOT IT!");
                }
                if (node.children && node.children.length > 0) {
                    for (var i = 0; i < node.children.length; i++) {
                        getNodePath(node.children[i]);
                    }
    
                    //当前节点的子节点遍历完依旧没找到,则删除路径中的该节点
                    temppath.pop();
                }
                else {
    
                    //找到叶子节点时,删除路径当中的该叶子节点
                    temppath.pop();
                }
            }
            getNodePath(catalog);
        }
        catch (e) {
            var result = temppath.join("\");
            callback(result);
        }
    };
    

      最后,只是给大家提供思路,过滤条件可以自己去定义

  • 相关阅读:
    将查询语句创建新表
    java冒泡排序
    java三元运算符
    java中的>>>和>>>=
    i++和++i
    设计4个线程,其中两个线程每次对j增加1,另外两个线程对j每次减少1。
    System.out.println与System.err.println的区别
    try-catch-finally
    Java常见异常类
    Vue.js环境配置
  • 原文地址:https://www.cnblogs.com/lycnblogs/p/6874389.html
Copyright © 2011-2022 走看看