简单算法 二叉树根节点到叶子节点和为指定值的路径(java)
描述
给定一个二叉树和一个值\ sum sum,请找出所有的根节点到叶子节点的节点值之和等于\ sum sum 的路径,
例如:
给出如下的二叉树
返回
[
[5,4,11,2],
[5,8,9]
]
想法:通过dfs遍历来完成。代码1:是从上往下减数。代码2:从上往下加数.两个方法差别不大
代码1:
public ArrayList<ArrayList<Integer>> pathSum (TreeNode root, int sum) {
// write code here
ArrayList<ArrayList<Integer>> result = new ArrayList<>();
dfs(root, sum, new ArrayList<>(), result);
return result;
}
public void dfs(TreeNode root, int sum, List<Integer> list,
List<ArrayList<Integer>> result) {
if(root == null) return;
list.add(new Integer(root.val));
if(root.left == null && root.right == null){
if(root.val == sum) result.add(new ArrayList(list));
list.remove(list.size() - 1);
return;
}
dfs(root.left,sum - root.val,list,result);
dfs(root.right,sum - root.val,list,result);
list.remove(list.size() - 1);
}
代码2:
public ArrayList<ArrayList<Integer>> pathSum (TreeNode root, int sum) {
// write code here
ArrayList<ArrayList<Integer>> result = new ArrayList<>();
dfs(root, sum, 0, new ArrayList<>(), result);
return result;
}
public void dfs(TreeNode root, int sum, int toal, List<Integer> list,
List<ArrayList<Integer>> result) {
if(root == null) return;
list.add(new Integer(root.val));
toal = toal + root.val;
if(root.left == null && root.right == null){
if(toal == sum) result.add(new ArrayList(list));
list.remove(list.size() - 1);
return;
}
dfs(root.left,sum,toal,list,result);
dfs(root.right,sum,toal,list,result);
list.remove(list.size() - 1);
}