zoukankan      html  css  js  c++  java
  • 多叉树到指定节点的路径

    基本上是使用深度优先遍历的套路,以下方法获取的是沿途的所有节点

    export function getPathNodesByKey(root,stack,fCompare) {
        let b = false;
        if (root != null) {  
            stack.push(root);  
            if(fCompare(root)){return true}
            var children = root.children;
            if(children){
                for (var i = 0; i < children.length; i++){
                    b = getPathByKey(children[i],stack,fCompare);  
                    if(b){
                        break;
                    }
                } 
            }  
            if(!b){
                stack.pop();
            } 
        }  
        return b;
    }
    
    export function getAllPathNodesByKey(root,stack,fCompare) {
        let b = false;
        if (root != null) {  
            stack.push(root);  
            if(fCompare(root)){return true}
            var children = root.children;
            if(children){
                for (var i = 0; i < children.length; i++){
                    b = getAllPathByKey(children[i],stack,fCompare);
                } 
            }  
            if(!b){
                stack.pop();
            } 
        }  
        return b;
    }

    获取沿途所有路径

    function getAllPathByKey(root,stack,fCompare,res) {
        if(root == null){
            return;
        }
        stack.push(root);  
        if(fCompare(root)){
            res.push(JSON.parse(JSON.stringify(stack)));
            return;
        }
        var children = root.children;
        if(children){
            for (var i = 0; i < children.length; i++){
                getAllPathByKey(children[i],stack,fCompare,res);  
                stack.pop();
            } 
        }  
    }
    
    function getFisrtPathByKey(root,stack,fCompare,res) {
        if(root == null){
            return;
        }
        stack.push(root);  
        if(fCompare(root)){
            res.push(JSON.parse(JSON.stringify(stack)));
            return true;
        }
        var children = root.children;
        if(children){
            for (var i = 0; i < children.length; i++){
                let hasNode = getFisrtPathByKey(children[i],stack,fCompare,res);  
                stack.pop();
                if(hasNode){
                    return true;
                }
            } 
        }  
    }

  • 相关阅读:
    [javaSE] GUI(jar包双击运行)
    [javaSE] GUI(打开文件对话框)
    [javaSE] GUI(菜单)
    [javaSE] GUI(对话框Dialog)
    [javaSE] GUI(练习-列出指定目录内容)
    [javaEE] 控制浏览器缓存资源
    [javaEE] response实现图片下载
    [javaSE] GUI(鼠标事件)
    [javaSE] 网络编程(TCP-并发上传图片)
    [javaSE] IO流(装饰设计模式)
  • 原文地址:https://www.cnblogs.com/mengff/p/12204728.html
Copyright © 2011-2022 走看看