Click to See Complete Forum and Search --> : A question with binary tree


LarryChen
December 4th, 2005, 04:51 PM
How to generate the postfix traversal given the prefix and infix traversals of a tree? Please give me some ideas. Thank you very much!

Ejaz
December 5th, 2005, 12:54 AM
Take a look at this (http://www.codepedia.com/1/Art_Expressions_p1)

mehdi62b
December 5th, 2005, 07:07 AM
this one is infix-->postfix[C#]
private string infixtopostfix(string input)
{
Stack st=new Stack();
string result=string.Empty;
for(int i=0;i<input.Length;i++)
{
if(char.IsLetter(input,i))
result+=input[i].ToString();
else
{
if(st.Count==0)
st.Push(input[i]);
else
{
while(st.Count!=0 && precedency((char)st.Peek(),input[i]))
{
result+=(char)st.Pop();
}
st.Push(input[i]);
}
}
}
while(st.Count!=0)
result+=(char)st.Pop();
return result;
}
private bool precedency(char ch1,char ch2)
{
if (ch1=='*' || ch1=='/')
return true;
if(ch1=='+' || ch1=='-')
if(ch2=='+' || ch2=='-')
return true;
return false;
}
//input : a+b*c-d
//output: abc*+d-this one compute the postfix strings[C#]
private int computePostFix(string input)
{
Stack st=new Stack();
Regex re=new Regex(@"(\d+)|([+\-*/])",RegexOptions.None);
Regex reNumber=new Regex(@"^(\d+)$",RegexOptions.None);
Regex reOp=new Regex(@"^[+\-*/]$",RegexOptions.None);
foreach(Match m in re.Matches(input))
{
if(reNumber.IsMatch(m.Value))
{
st.Push(m.Value);
}
else
{
if(reOp.IsMatch(m.Value))
{
string value1=(string)st.Pop();
string value2=(string)st.Pop();
int v1=int.Parse(value1);
int v2=int.Parse(value2);
int result=0;
switch (m.Value)
{
case "+":
result=v1+v2;
break;
case "-":
result=v1-v2;
break;
case "*":
result=v1*v2;
break;
case "/":
result=v2/v1;
break;
}
st.Push(result.ToString());

}
}
}
string r=(string)st.Pop();
return int.Parse(r);
}