二进制搜索树路径列表

编程入门 行业动态 更新时间:2024-10-23 16:14:59
本文介绍了二进制搜索树路径列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

这是在二叉树中获取所有从根到叶的路径的代码,但它会将所有串联在一起的路径放入一个路径中.递归调用怎么了?

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

更多推荐

二进制搜索树路径列表

本文发布于:2023-11-29 08:25:44,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1645864.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:路径   列表

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!