本文介绍了二进制搜索树路径列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是在二叉树中获取所有从根到叶的路径的代码,但它会将所有串联在一起的路径放入一个路径中.递归调用怎么了?
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); } } 推荐答案您将对所有路径使用相同的 l 列表,这些列表将不起作用,您必须在每次调用递归时创建一个新的:
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); }更多推荐
二进制搜索树路径列表
发布评论