其他分享
首页 > 其他分享> > 【剑指offer】二叉树中和为某一值的路径

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

作者:互联网

题目描述

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

题解

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>> res = new ArrayList<ArrayList<Integer>>();
        ArrayList<Integer> currentPath = new ArrayList<Integer>();
        find(root, res, target, currentPath, 0);
        return res;
    }
    
    private void find(TreeNode node, ArrayList<ArrayList<Integer>> res, 
                      int expectedSum, ArrayList<Integer> currentPath, 
                      int currentSum) {
        if(node == null)
            return;
        currentSum += node.val;
        currentPath.add(node.val);
        if(node.left == null && node.right == null) {
            if(currentSum == expectedSum)
                res.add(new ArrayList<Integer>(currentPath));
        } else {
            if(node.left != null)
                find(node.left, res, expectedSum, currentPath, currentSum);
            if(node.right != null)
                find(node.right, res, expectedSum, currentPath, currentSum);
        }

        currentSum -= node.val;
        currentPath.remove(currentPath.size()-1);
    }
}

 

标签:node,val,offer,currentPath,ArrayList,二叉树,res,null,一值
来源: https://blog.csdn.net/sun_lm/article/details/100516362