给定一个二叉树和一个目标和,求节点路径

image.png

今天有幸徒手在记事本编程,大概完成了上面的算法逻辑,思路还是很简单,大家看看对不对

void main(String[] args){
    List<List<TreeNode>> result=new ArrayList<>();

    List<List<TreeNode>> paths=findPath(root);
    while(paths.size()>0){
        List<TreeNode> path=paths[0];
        paths.removeAt(0);
        //验证是否满足要求
        int sumNum=calSum(path);
        if(sumNum==22){
            result.add(path);
            continue;
        }
        TreeNode lastNode=path.get(path.size()-1);
        List<List<TreeNode>> tempPaths=findPath(lastNode);
        //移除最后一个
        path.removeAt(path.size()-1);
        for(List<TreeNode> tempPath:tempPaths){
            List<TreeNode> newPath=new ArrayList();
            newPath.addRange(path);
            newPath.addRange(tempPath);
            paths.add(newPath);
        }
    }
    
    for(List<TreeNode> nodes:result){
        String s=StringUtils.join(",",nodes.stream().map(p->p.value).toArray());
        System.out.printIn(s);
    }
}
int calSum(List<TreeNode> nodes){
    int sum=0;
    for(TreeNode node:nodes){
        sum+=node.value;
    }
    return sum;
}
void List<List<TreeNode>> findPath(TreeNode root){
    List<List<TreeNode>> nodes=new ArrayList();
    if(root.left!=null && root.right!=null){
        List<TreeNode> leftNodes=new ArrayList(); 
        List<TreeNode> rightNodes=new ArrayList(); 
        
        leftNodes.add(root);
        leftNodes.add(root.left)
        
        rightNodes.add(root);
        rightNodes.add(root.right);
        
        nodes.add(leftNodes);
        nodes.add(rightNodes);
    }
    else if(root.left!=null || root.right!=null){
        List<TreeNode> tempNodes=new ArrayList(); 
        tempNodes.add(root);
        tempNodes.add(root.left!=null?root.left:root.right);
        
        nodes.add(tempNodes);
    }
    return nodes;
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 无意中知道了一个软件叫做百词斩,是背英语单词用的。我从中考的词汇开始背起,从现在开始我要每天坚持我要坚持我要坚...
    醒来的自己阅读 355评论 0 0
  • 《心灵易经》读书打卡第14天 出离心 每个人被事业支配,被情绪支配,被思维支配,被欲望支配...
    六月荷花草阅读 216评论 0 1
  • “从这里到那里,怎么坐车?” “这个路边的英语广告牌写的是什么内容?” “这个表格我不会做,你每天都在做财务表格,...
    Candy周_践行阅读 1,558评论 0 1
  • 我是85后,从小在城市长大。小时候,跟着姥姥回农村。麦地里,姥姥叹着气说“你们这代不行了,连秧苗都分不清。”回到家...
    迟迟白日晚阅读 724评论 2 5
  • 前些日子,紫薇和我说:简浅,我要离开北京了。 想起去年我去北京找她时,她正和我说想要离开结果还是被劝下来了,一年没...
    简浅Jian阅读 359评论 0 2