- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
为什么最后使用“path.remove(path.size()-1)”?
此代码用于查找总和等于给定总和的所有根到叶路径。
public List<List<Integer>> pathSum(TreeNode root, int sum) {
List<List<Integer>> res = new ArrayList<List<Integer>>();
ArrayList<Integer> path = new ArrayList<Integer>();
pathSumRe(root, sum, res, path);
return res;
}
public void pathSumRe(TreeNode root, int sum, List<List<Integer>> res,
ArrayList<Integer> path) {
if (root == null)
return;
path.add(root.val);
if (root.left == null && root.right == null && root.val == sum) {
ArrayList<Integer> tmp = new ArrayList<Integer>(path);
res.add(tmp);
}
pathSumRe(root.left, sum - root.val, res, path);
pathSumRe(root.right, sum - root.val, res, path);
path.remove(path.size() - 1);
}
删除“path.remove(path.size() - 1);”代码将给出以下输出。
输入:[0,1,1], 1
输出:[[0,1],[0,1,1]] ==>这是错误的输出
预期输出:[[0,1],[0,1]]
最佳答案
path.remove(path.size() - 1)
正在从 path
列表中删除最后添加的节点,因为您对所有节点重复使用相同的列表递归迭代,并在每个方法执行中使用 path.add(root.val);
添加当前节点。
以下内容是等效的,无需重复使用相同的列表(并为每次执行创建一个新列表):
public void pathSumRe(TreeNode root, int sum, List<List<Integer>> res,
ArrayList<Integer> path) {
if (root == null) {
return;
}
path.add(root.val);
if (root.left == null && root.right == null && root.val == sum) {
res.add(new ArrayList<Integer>(path));
}
pathSumRe(root.left, sum - root.val, res, new ArrayList<Integer>(path));
pathSumRe(root.right, sum - root.val, res, new ArrayList<Integer>(path));
}
这更容易理解,但会创建更多新的 ArrayList(取决于树结构)。无论您进行何种编辑,两个版本都可以正确地用于如下所示的 TreeNode:
class TreeNode {
public final int val;
public final TreeNode left;
public final TreeNode right;
public TreeNode(int val, TreeNode left, TreeNode right) {
this.val = val;
this.left = left;
this.right = right;
}
}
关于java - 给定一棵二叉树和一个总和,找到所有根到叶路径,其中每个路径的总和等于给定的总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32002254/
我正在尝试从底层叶进程写入命名管道并从顶层进程的管道读取。 为此,我首先在顶级进程中创建 FIFO,然后使用 for 循环派生更多进程。在 for 循环中,我正在检查叶子进程,如果它是叶子,我正在写入
我需要一个XPath表达式来验证XML列表元素是否只有某种类型的节点。 例: 我需要知道列表中是否只有图像。
我想从层次结构表中获取所有叶子及其根。叶子是最低层节点,根是最顶层节点。 给定一棵树: A --B --C --D E --F --G --H 叶子是节点:C, D根是:A、E 该表如下所
尝试从嵌套数组中删除相同的 sibling (叶子)/相同的数组。 例如 $data = [ 'test' => [ 'a' => [
我可以遍历目录并只打印文件夹/目录名称,但我想排除包含其他目录的目录的文件夹名称。出于某种原因,我称其为树结构中的“最终节点”,但我很可能是在自欺欺人,这不是第一次了。 =) 在审查其他答案列表时,也
我现在经常使用 Folium,在 Python 中拥有如此易于使用的东西真的很棒。但是他们的文档严重落后,我理解。所以我有2个问题。 我在尝试获得更多标记颜色时做错了什么?这是我尝试过的:map.si
我正在尝试使用 ape 包中的 plot.phylo 命令为 R 中系统发育类型图的边缘(线)添加颜色。这个例子是一个“粉丝”类型的图,虽然我希望这个方法与“系统图类型”或其他任何东西相同。 libr
我正在尝试呈现一个 JTree 叶以具有包含可编辑 JTextArea 的 JPanel,以便用户可以输入文本并能够在添加文本时向下滚动, 并且还使用包装器来限制文本的宽度,使其向下延伸以留出更多空间
这是要修改的正确 Linux 内核代码吗?我如何进行更改以模拟 CPUID 代码以及我需要更改哪个函数。谢谢 #include #include #include #include #incl
我是一名优秀的程序员,十分优秀!