24.二叉树中和为某一值的路径(java)

题目描述

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

解题思路

相当于带记忆的DFS。

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

    public TreeNode(int val) {
        this.val = val;

    }

}
*/
public class Solution {
    public ArrayList<ArrayList<Integer>> FindPath(TreeNode root,int target) {
        ArrayList<ArrayList<Integer>>result = new  ArrayList<ArrayList<Integer>>();
        ArrayList<Integer> temp = new ArrayList<Integer>();
        if(root!=null)
            dfs(root,target,result,temp);
        return result;
    }
    public void dfs(TreeNode root,int target ,ArrayList<ArrayList<Integer>> result, ArrayList<Integer> temp)
    {
        temp.add(root.val);
        if(root.left==null&&root.right==null)
        {
            if(target==root.val)
            {
                result.add(temp);
            }
            return;
        }
        ArrayList<Integer> path=new ArrayList<>();
        path.addAll(temp);//new一个path,让它和temp相等,然后分别负责left和right分支的递归。
        if(root.left!=null)
            dfs(root.left,target-root.val,result,temp);
        if(root.right!=null)
            dfs(root.right,target-root.val,result,path);
    }
}
发布了43 篇原创文章 · 获赞 0 · 访问量 460

猜你喜欢

转载自blog.csdn.net/gaopan1999/article/details/104501117