【问题标题】:binary search tree path list二叉搜索树路径列表
【发布时间】:2018-06-16 08:57:19
【问题描述】:

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

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

    }

}

【问题讨论】:

    标签: java algorithm arraylist binary-tree


    【解决方案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);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多