【发布时间】:2016-09-07 05:09:57
【问题描述】:
有一个关于二叉树的基本java示例的问题:给定一棵二叉树,找到路径中节点之和等于给定数字目标的所有路径。(有效路径是从根节点到任何一个叶节点。)。
为什么我们需要path.remove(path.size() - 1);当它经过左右节点时?
这里是代码示例:
public class Solution {
public List<List<Integer>> binaryTreePathSum(TreeNode root, int target) {
List<List<Integer>> result = new ArrayList<>();
if (root == null) {
return result;
}
ArrayList<Integer> path = new ArrayList<Integer>();
path.add(root.val);
helper(root, path, root.val, target, result);
return result;
}
private void helper(TreeNode root,
ArrayList<Integer> path,
int sum,
int target,
List<List<Integer>> result) {
// meet leaf
if (root.left == null && root.right == null) {
if (sum == target) {
result.add(new ArrayList<Integer>(path));
}
return;
}
// go left
if (root.left != null) {
path.add(root.left.val);
helper(root.left, path, sum + root.left.val, target, result);
path.remove(path.size() - 1);
}
// go right
if (root.right != null) {
path.add(root.right.val);
helper(root.right, path, sum + root.right.val, target, result);
path.remove(path.size() - 1);
}
}
}
【问题讨论】:
标签: java binary-tree