binary search tree path list

僤鯓⒐⒋嵵緔 提交于 2021-01-27 13:47:36

问题


This is code to get all the root to leaf paths in a Binary Tree but it puts in all the paths concatenated into one path. What is going wrong with the recursive call?

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:


You're reusing the same l list for all the paths, that won't work, you must create a new one every time the recursion gets called:

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


来源:https://stackoverflow.com/questions/48132359/binary-search-tree-path-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!