【剑指offer】二叉树中和为某一值的路径

题目描述

输入一颗二叉树的跟节点和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。(注意: 在返回值的list中,数组长度大的数组靠前)

分析

github地址:https://github.com/xlrainy123/algorithms-implement-by-java/tree/master/src/main/java

package 二叉树的路径之和等于指定值;

import tree.TreeNode;
import java.util.*;

public class Solution {

    public ArrayList<ArrayList<Integer>> FindPath(TreeNode root,int target) {
        ArrayList<ArrayList<Integer>> result = new ArrayList<>();
        ArrayList<Integer> path = new ArrayList<>();
        if (root == null){
            return result;
        }
        dfs(root, target, result, path, 0);
        return result;
    }

    public void dfs(TreeNode root, int target, ArrayList<ArrayList<Integer>> result, ArrayList<Integer> path, int currentSum){
        TreeNode pNode = root;
        if (pNode != null){
            path.add(pNode.val);
            currentSum += pNode.val;
            if (target - currentSum == 0 && pNode.left == null && pNode.right == null){
                result.add(new ArrayList<>(path));
            }
            dfs(root.left, target, result, path, currentSum);
            dfs(root.right, target, result, path, currentSum);
            path.remove(path.size()-1);
        }
    }
}

猜你喜欢

转载自blog.csdn.net/Shannon076/article/details/81057515
今日推荐