【发布时间】:2016-09-11 14:38:17
【问题描述】:
问题一棵树
可以用带括号的字符串表达式表示
(D(B(A)(C))(E()(F(G()(H)))))
注意:没有值的大括号,如上面表达式中的 (),表示一个空子指针,左或右,取决于符号的位置。
这是我目前所拥有的
static public Stack list = new Stack();
static void Main(string[] args)
{
//ArrayList list = new ArrayList();
StreamReader RW = new StreamReader("Trees.txt");
//Stack checkList = new Stack();
while(!RW.EndOfStream)
{
string tmp = RW.ReadLine();
BTNode T = null;
doTree(tmp, 0, ref T);
//doTree(tmp, T, 0, null, checkList);
//list.Add(T);
}
}
static private void doTree(string str,int num, ref BTNode T)
{
if(num>=str.Length)
{
return;
}
if (str[num] == '(')
{
if (num == 0)
{
T = new BTNode(str[num + 1]);
list.Push(T);
doTree(str, num + 2, ref T);
}
else if ((str[num + 1] != ')')&&(str[num+3]!='('))
{
BTNode temp = new BTNode(str[num + 1]);
T.setLeft(temp);
temp.setParent(T);
list.Push(temp);
doTree(str, num + 2, ref temp);
}
else
{
doTree(str, num + 1,ref T);
}
}
else if ((((str[num] == ')'))&&(str[num+2]!=')')))
{
BTNode par = (BTNode)list.Pop();
BTNode temp = new BTNode(str[num +2]);
par.setRight(temp);
temp.setParent(par);
doTree(str, num + 4, ref temp);
}
else
{
doTree(str, num + 6, ref T);
list.Pop();
}
}
谁能帮忙
【问题讨论】:
标签: java tree binary-tree