Your are given a binary tree in which each node contains a value. Design an algorithm to get all paths which sum to a given value. The path does not need to start or end at the root or a leaf, but it must go in a straight line down.
Example
Given a binary tree:
1
/ \
2 3
/ /
4 2
for target = 6,
return
注意点:该题目在计算获得 target == 0 后,不能直接返回,需要在继续向下寻找
java
public class Solution {
/*
* @param root: the root of binary tree
* @param target: An integer
* @return: all valid paths
*/
public List<List<Integer>> binaryTreePathSum2(TreeNode root, int target) {
// write your code here
List<List<Integer>> result = new ArrayList<>();
if (root == null) {
return result;
}
List<TreeNode> preorder = preOrder(root);
List<Integer> path = new ArrayList<>();
for (TreeNode node : preorder) {
path.add(node.val);
dfs(result, path, target - node.val, node);
path.clear();
}
return result;
}
private List<TreeNode> preOrder(TreeNode root) {
List<TreeNode> result = new ArrayList<>();
if (root == null) {
return result;
}
List<TreeNode> left = preOrder(root.left);
List<TreeNode> right = preOrder(root.right);
result.add(root);
result.addAll(left);
result.addAll(right);
return result;
}
private void dfs(List<List<Integer>> result, List<Integer> path,
int target, TreeNode root) {
if (target == 0) {
result.add(new ArrayList<Integer>(path));
}
if (root == null) {
return;
}
if (root.left != null) {
path.add(root.left.val);
dfs(result, path, target - root.left.val, root.left);
path.remove(path.size() - 1);
}
if (root.right != null) {
path.add(root.right.val);
dfs(result, path, target - root.right.val, root.right);
path.remove(path.size() - 1);
}
}
}
本文介绍了一种算法,用于查找二叉树中所有节点值之和等于给定目标值的路径。路径无需从根节点开始或在叶节点结束,但必须沿直线向下延伸。文章提供了Java实现代码。

304

被折叠的 条评论
为什么被折叠?



