leetcode 113. Path Sum II

Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum.

For example:
Given the below binary tree and sum = 22,
              5
             / \
            4   8
           /   / \
          11  13  4
         /  \    / \
        7    2  5   1

return

[
   [5,4,11,2],
   [5,8,4,5]
]

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public List<List<Integer>> pathSum(TreeNode root, int sum) {
         
         List<List<Integer>> list=new ArrayList<List<Integer>>();
         List<Integer> li=new ArrayList<Integer>();
         if(root==null) return list;
         int currentSum=0;
        find(root,sum,currentSum,li,list);
        return list;
    }
    public static void find(TreeNode root,int sum,int currentSum,List<Integer> li,List<List<Integer>> list){
        currentSum+=root.val;
        li.add(root.val);
        boolean isLeaf=root.left==null&&root.right==null;
        if(currentSum==sum&&isLeaf){
           List<Integer> ls=new ArrayList<Integer>(li);
           list.add(ls);
        }
        if(root.left!=null)
          find(root.left,sum,currentSum,li,list);
          if(root.right!=null)
          find(root.right,sum,currentSum,li,list);
           li.remove(li.size()-1);
    }
}


思路:用前序遍历的方式访问某一个节点时,吧该节点添加到路径上,并累加该节点的值,如果该节点为叶子节点并且路径中节点的值刚好等于

输入的整数,当前的路径符合要求。如果当前不是叶子节点,则继续访问它的叶子节点。当前节点访问结束后,递归函数将自动回到它的父节点。因此我们在函数退出之前要在路径上删除当前节点并减去当前节点的值,刚好是从根节点到父节点的路径。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值