您的位置:首页 > 编程语言 > Java开发

[LeetCode][Java] Path Sum II

2015-07-21 10:48 627 查看

题目:

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]
]

题意:

给定一棵二叉树和一个和,找出从根节点到叶子节点的遍历中节点值的和等于给定目标值的所有的路径。

比如:

给定如下的二叉树和
sum = 22
,

5
/ \
4   8
/   / \
11  13  4
/  \    / \
7    2  5   1

返回

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


算法分析:

* 同题目《Path Sum》相似

* 同样利用递归策略

* 不同之处在于本题需要在遍历的时候记录走寻的路径 dfs

* 但是需要注意的是,递归回溯上来的时候要进行清理工作

AC代码:

/**
* Definition for binary tree
* public class TreeNode {
*     int val;
*     TreeNode left;
*     TreeNode right;
*     TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public ArrayList<ArrayList<Integer>> pathSum(TreeNode root, int sum) {
ArrayList<ArrayList<Integer>> res=new ArrayList<ArrayList<Integer>>();
helper(root,sum,new ArrayList<Integer>(),res);
return res;
}

public void helper(TreeNode root,int sum,ArrayList<Integer> cur,ArrayList<ArrayList<Integer>> res)
{
if(root==null)
return;
//到达叶子节点且根结点的值等于sum
if(root.left==null && root.right==null && root.val==sum)
{
cur.add(root.val);
res.add(new ArrayList<Integer>(cur));
//清除操作
cur.remove(cur.size()-1);
return;
}
//没有到达叶子节点,左子树不为空
if(root.left!=null)
{
cur.add(root.val);
//对左子树进行递归调用
helper(root.left,sum-root.val,cur,res);
//返回时,清除操作
cur.remove(cur.size()-1);
}
//没有到达叶子节点,右子树不为空
if(root.right!=null)
{
cur.add(root.val);
//对右子树进行递归调用
helper(root.right,sum-root.val,cur,res);
//返回时,清除操作
cur.remove(cur.size()-1);
}

}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: