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

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

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

import java.util.*;

/*
 * 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<>>
     */
    ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>();
    public ArrayList<ArrayList<Integer>> pathSum (TreeNode root, int sum) {
        // write code here
        if(root == null) {
            return res;
        }
        ArrayList<Integer> path = new ArrayList<Integer>();
        dfs(root,sum,path);
        return res;

    }

    public void dfs(TreeNode root, int sum, ArrayList<Integer> path) {
        // write code here
        if(root == null) return ;
        sum -= root.val;
        path.add(root.val);


        if(root.left == null && root.right == null) {
            if(sum == 0 ){
                res.add(new ArrayList<Integer>(path));
            }
        }else {
            dfs( root.left,  sum,  path);
            dfs( root.right,  sum,  path);
        }

        path.remove(path.size()-1);


    }
}
全部评论

相关推荐

01-04 21:30
已编辑
河南工业大学 Java
27届学院本誓死冲击...:下次再发把个人信息隐藏掉,以防有心之人。相关课程删了,荣誉奖项只留蓝桥杯,把蓝桥杯写到教育经历里,按教育经历、实习经历、项目经历、专业技能这个顺序排版
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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