【发布时间】:2016-11-23 02:17:43
【问题描述】:
我希望将二叉搜索树的值按顺序存储在列表中。 我有一个调用辅助方法的公共方法,但是当我打印返回的列表时,我不断得到一个空列表...
public List inOrderList(){
return inOrderList(overallRoot); //root value
}
private List inOrderList(SearchTreeNode root){
List<E> list1 = new ArrayList<E>(); //new list (will be returned)
if(root==null){
return list1; //returns empty list
}
//List is NOT empty, let's do this thing.
else {
//create a new list, that calls left method recursive on left node
List<E> podo = inOrderList(root.left);
//Here, I *believe* we've reached the bottom. Add every podo to list1
list1.addAll(podo);
//do the same thing for the right tree
List<E> dopo = inOrderList(root.right);
list1.addAll(dopo);
}
//return the list we just filled from our BST
return list1;
}
我选择不尝试仅用数据填写我的列表。我认为使用addAll 并以这种方式存储所有内容将是一个更好的选择。鉴于此解决方案不起作用,我也尝试存储数据。
private List<Integer> inOrderList(IntTreeNode root){
List<Integer> list1 = new ArrayList<Integer>();
if(root==null){
return list1;
} else {
while(root!=null){
List<Integer> podo = inOrderList(root.left);
list1.add(root.data);
List<Integer> dopo = inOrderList(root.right);
list1.add(root.data);
}
}
return list1;
}
我发现这至少填充了 a 列表,但是它只是将根值插入了两次并完成了。过去一个小时左右我一直在研究这个问题,但似乎找不到更好的办法,所以我想我会求助于你们。
我哪里出错了/我应该怎么做?
【问题讨论】:
-
你尝试调试了吗?
-
您可以尝试将 List1
对象作为第二个参数传递给您的 inOrderList 方法,而不是在每次递归调用时创建一个 List 吗?我指的是您的第二个解决方案。 -
添加第二个参数希望做什么?
-
没什么,只是会进一步减少代码行数并帮助您集中/调试未按预期工作的部分。
-
我一直用 println 调试,让我看到我在代码中的位置。我不熟悉你指的是什么。我会试一试并报告
标签: java list binary-search-tree