二叉树中和为某一值的路径_JAVA_较难

二叉树中和为某一值的路径

http://www.nowcoder.com/questionTerminal/b736e784e3e34731af99065031301bca

  • 递归解决
import java.util.ArrayList;
public class Solution {
    public ArrayList<ArrayList<Integer>> FindPath(TreeNode root,int target) {
        ArrayList<ArrayList<Integer>> res = new ArrayList();
        ArrayList<Integer> cache = new ArrayList();
        FindPathRes(root, target, res, cache);
        return res;
    }

    public void FindPathRes(TreeNode root,int target,ArrayList<ArrayList<Integer>> res, ArrayList<Integer> cache) {
        if(root == null) {
            return;
        }
        cache.add(root.val);

        // 结果符合则输出
        if(target == root.val && !cache.isEmpty() && root.left == null && root.right == null) {
            ArrayList<Integer> list = new ArrayList();
            list.addAll(cache);
            res.add(list);
        }
        FindPathRes(root.left, target - root.val, res, cache);
        FindPathRes(root.right, target - root.val, res, cache);
        cache.remove(cache.size() - 1);
    }
}
全部评论

相关推荐

MScoding:你这个实习有一个是当辅导老师,这个和找技术岗没有关系吧?
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务