卡在binarysearchtree实现*Java上*
我正在做我的作业,我的最后一个问题要求我写一个程序,使用二进制字符搜索树您将从输入中读取一系列字符, 表示二叉搜索树的前序遍历。您需要从恢复二进制搜索树的原始形状 按此顺序,以横向(如下图所示)和顺序打印树的内容。 IPPublic类横向打印{卡在binarysearchtree实现*Java上*,java,binary-search-tree,Java,Binary Search Tree,我正在做我的作业,我的最后一个问题要求我写一个程序,使用二进制字符搜索树您将从输入中读取一系列字符, 表示二叉搜索树的前序遍历。您需要从恢复二进制搜索树的原始形状 按此顺序,以横向(如下图所示)和顺序打印树的内容。 IPPublic类横向打印{ public static void main(String[] args) { if(args.length == 0 || args[0].length() == 0) { throw new IllegalArg
public static void main(String[] args) {
if(args.length == 0 || args[0].length() == 0)
{
throw new IllegalArgumentException ("This is an invalid argument");
}
String chars = args[0];
BinarySearchTree<StringItem, String> bst = new BinarySearchTree<StringItem, String>();
publicstaticvoidmain(字符串[]args){
如果(args.length==0 | | args[0].length()==0)
{
抛出新的IllegalArgumentException(“这是一个无效参数”);
}
字符串字符=args[0];
BinarySearchTree bst=新的BinarySearchTree();
这是我收到的框架代码,我在其中添加了异常行。我不确定如何启动此代码,因为我在binarysearchtrees方面很弱。具体来说,我不知道如何在参数中使用StringItem方法。这是提供的StringItem方法
public class StringItem extends KeyedItem<String> {
public StringItem(String str) {
super(str);
}
public String toString(){
return getKey()+"";
}
} // end StringItem
public类StringItem扩展了KeyedItem{
公共字符串项(字符串str){
超级(str);
}
公共字符串toString(){
返回getKey()+“”;
}
}//结束项
非常感谢您提供一些详细的解释:)谢谢。这里有一个C语言的快速实现,但是您仍然需要调整它以满足您的结构需要。您仍然应该了解算法的概念,或者如果您遇到问题,我可以试着解释:
private BinaryTreeNode<int> ReconstructPreorderRecursive(List<int> inorder, List<int> preorder, int inorderStart, int inorderEnd)
{
BinaryTreeNode<int> root = new BinaryTreeNode<int>();
root.Value = preorder[preorderIndex];
int index = inorder.IndexOf(preorder[preorderIndex]);
//left subtree
if (index > inorderStart)
{
preorderIndex++;
root.LeftChild = ReconstructPreorderRecursive(inorder, preorder, inorderStart, index - 1);
if (root.LeftChild != null)
root.LeftChild.Parent = root;
}
//right subtree
if (index < inorderEnd)
{
preorderIndex++;
root.RightChild = ReconstructPreorderRecursive(inorder, preorder, index + 1, inorderEnd);
if (root.RightChild != null)
root.RightChild.Parent = root;
}
return root;
}
我相信如果谷歌itI刚刚完成中缀到后缀转换器/计算器的编码并开始讨论这个问题,你会发现一些很好的例子。有一件事我真的不明白,那就是将树打印为横向输出。我该怎么做呢..谢谢你的解释:)。但我想我会放弃这个问题,因为我没有太多时间了。我会eed将从二叉树的基础重新开始。
newTree.Root = ReconstructPreorderRecursive(lstInorder, lstPreorder, 0, lstInorder.Count - 1);