gpt4 book ai didi

java - 二叉搜索树路径列表

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:55:40 25 4
gpt4 key购买 nike

这是获取二叉树中所有根到叶路径的代码,但它将所有路径串联成一个路径。递归调用出了什么问题?

private void rec(TreeNode root,List<Integer> l, List<List<Integer>> lists) {
if (root == null) return;

if (root.left == null && root.right == null ) {
l.add(root.val);
lists.add(l);
}

if (root.left != null) {
l.add(root.val);
rec(root.left,l,lists);

}
if (root.right != null) {
l.add(root.val);
rec(root.right,l,lists);

}

}

最佳答案

您正在为所有路径重用相同的 l 列表,这是行不通的,您必须在每次调用递归时创建一个新列表:

if (root.left != null) {
List<TreeNode> acc = new ArrayList<>(l);
acc.add(root.val);
rec(root.left, acc, lists);
}

if (root.right != null) {
List<TreeNode> acc = new ArrayList<>(l);
acc.add(root.val);
rec(root.right, acc, lists);
}

关于java - 二叉搜索树路径列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48132359/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com