您的位置:首页 > 其它

Binary Tree Path Sum II

2018-01-03 20:56 274 查看
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.

Have you met this question in a real interview? 

Yes

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