java 深度优先搜索dfs

二叉树根节点到叶子节点和为指定值的路径

http://www.nowcoder.com/questionTerminal/840dd2dc4fbd4b2199cd48f2dadf930a

import java.util.*;
import java.util.ArrayList;
/*
 * public class TreeNode {
 *   int val = 0;
 *   TreeNode left = null;
 *   TreeNode right = null;
 * }
 */

public class Solution {
    /**
     * 
     * @param root TreeNode类 
     * @param sum int整型 
     * @return int整型ArrayList<ArrayList<>>
     */
    public ArrayList<ArrayList<Integer>> pathSum (TreeNode root, int sum) {
        // write code here
        ArrayList <ArrayList<Integer>> res=new  ArrayList<ArrayList<Integer>>();
        ArrayList<Integer> path=new ArrayList<Integer>();
        if(root==null)return res;
        path.add(root.val);
        dfs(root,sum,path,res);
        return res;
    }
    public static void dfs(TreeNode root,int sum,ArrayList path,ArrayList <ArrayList<Integer>> res){
        if (root.left==null&&root.right==null &&sum(path)==sum){
            res.add(new ArrayList<>(path));

        }
        if (root.left!=null){
            path.add(root.left.val);
            dfs(root.left,sum,path,res);
            path.remove(path.size()-1);//此处注意,和Python不同,需要自行移除
        }
        if (root.right!=null){
            path.add(root.right.val);
            dfs(root.right,sum,path,res);
            path.remove(path.size()-1);
        }

    }
    public static int sum(ArrayList list){//自己写一个求和函数
        int s=0;
        for(Object i:list){
            s+=(int)i;
        }
        return s;
    }
}
全部评论

相关推荐

缒梦&独舞:这家公司是这样的,去年给我实习offer了,不过也是面着玩儿的,他周六还要去做公益志愿活动
点赞 评论 收藏
分享
06-13 15:45
辽宁大学 golang
咱就是说&nbsp;你不主动&nbsp;我也不会主动下一步hhh,急死了
恶龙战士:不建议把这种帖子发到牛客上,建议去小红书发
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务