版权声明:转载请注明本文源地址 https://blog.csdn.net/qwe6112071/article/details/71599302
Binary Tree Path Sum
Description
Given a binary tree, find all paths that sum of the nodes in the path equals to a given number target.
A valid path is from root node to any of the leaf nodes.
Example
Given a binary tree, and target = 5:
1
/ \
2 4
/ \
2 3
return
[
[1, 2, 2],
[1, 4]
]
实现思路
进行先序遍历,遍历到每个叶子节点的时候,判断sum是否等于target,相等则添加到结果集中。
注意在回溯的时候,要删除当前层次添加的节点。
/**
* Definition of TreeNode:
* public class TreeNode {
* public int val;
* public TreeNode left, right;
* public TreeNode(int val) {
* this.val = val;
* this.left = this.right = null;
* }
* }
*/
public class Solution {
/**
* @param root the root of binary tree
* @param target an integer
* @return all valid paths
*/
int target;
List<List<Integer>> ret = new ArrayList<>();
public List<List<Integer>> binaryTreePathSum(TreeNode root, int target) {
if(root == null){
return ret;
}
this.target = target;
List<Integer> path = new ArrayList<>();
helper(path, root,0);
return ret;
}
public void helper(List<Integer> path, TreeNode root, int sum){
sum += root.val;
path.add(root.val);
if(root.left == null && root.right == null && sum == target){
List<Integer> newList = new ArrayList<>();
newList.addAll(path);
ret.add(newList);
}
if(root.left != null){
helper(path,root.left,sum);
}
if(root.right != null){
helper(path,root.right,sum);
}
path.remove(path.size() -1);
}
}