【发布时间】:2021-11-23 03:33:35
【问题描述】:
我得到一个字符串,例如: (((!D!)B!)A((!F(!H!))C(!G!))) ,其中从来没有任何空格。一种 '!'表示节点的那一侧没有子节点。为了形象化,前面提到的字符串看起来像:https://i.stack.imgur.com/WywYm.png
我必须有一个构造函数,可以调用递归方法通过传入String来构建树,这就是我这里的:
public BinaryTree(String tree) {
//build the tree from the inOrder representation of the tree
//in the inOrder representation an empty tree is ! and a non-empty tree is (leftdataright)
if(tree.charAt(0) == '!') root = null;
root = buildTree(tree).root;
}
从这里我通过私有 BuildTree 方法进入,该方法应该使用递归并返回对完全组装树的根的引用。我的代码是:
private BinaryTree buildTree(String tree) {
char data = tree.charAt(0);
BinaryTree b1;
BinaryTree b2;
if(tree.charAt(0) == '!') return new BinaryTree();
b1 = buildTree(tree.substring(1, tree.length()));
b2 = buildTree(tree.substring(1, tree.length()));
return new BinaryTree(b1, data, b2);
}
我想我对 InOrder 表示感到困惑,在这种表示形式中,您不会遇到完整树的根,直到您进入字符串非常远。我当前的代码没有做任何事情,我完全不知道如何在不立即知道根的情况下完成此操作。如果有人可以更好地解释这一点以使我更接近解决方案,请告诉我。谢谢。
【问题讨论】:
标签: java binary-tree inorder