我对构造函数不太熟悉。我们在整个学期都在使用各种方法。我想到这个的想法是: 1)检查字符串是否为空 2)将字符串转换为char数组 3)确定列表中的第一个char是根 4)将阵列的其余部分分成左右两侧(如果有多个)。 其余的我还没有考虑过,因为我在将char转换成节点时遇到了麻烦。该类不允许创建新节点,而是允许带参数的BinaryTree(数据,左,右)。我的下面的代码不能满足我的要求,只是为了给你一个想法。
public BinaryTree ( String preorderSequence ) {
String s = preorderSequence;
Node rootNode;
if (s.isEmpty())
return;
if (s.length() == 1)
rootNode = new Node(s.substring(0));
else{
String chars = s.substring(1);
String rootChar = Character.toString(s.charAt(0));
rootNode = new Node(rootChar);
Node low = null;
Node high = null;
String temp = Character.toString(chars.charAt(0));
//Get the lowest valued character and convert it into low node
for(int i = 0 ; i < chars.length(); i++){
String comp = Character.toString(chars.charAt(i));
if( comp.compareTo(temp) < 0 )
temp = comp;
}
low = new Node(temp);
//Get the highest valued character and convert it into the high node
for(int i = 0; i < chars.length(); i++){
String comp = Character.toString(chars.charAt(i));
if( comp.compareTo(temp) > 0)
temp = comp;
}
high = new Node(temp);
if(s.length()>3)
new BinaryTree(chars);
if(((String) rootNode.data).compareTo((String) low.data)<0){
rootNode.right = low;
low.right = high;
}
else
if(((String) rootNode.data).compareTo((String) high.data)>0){
rootNode.left = high;
high.left = low;
}
else{
rootNode.left = low;
rootNode.right = high;
}
}
root = rootNode;
}