二叉搜索树路径列表

时间:2018-01-06 22:03:21

标签: java algorithm arraylist binary-tree

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

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);

    }

}

1 个答案:

答案 0 :(得分:1)

你正在为所有路径重用相同的 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);
}
相关问题