<span style="font-size: 18px; font-family: Arial, Helvetica, sans-serif; background-color: rgb(255, 255, 255);">
</span>
<span style="font-size: 18px; font-family: Arial, Helvetica, sans-serif; background-color: rgb(255, 255, 255);"></span><pre code_snippet_id="495329" snippet_file_name="blog_20141024_1_8664932" name="code" class="csharp">对于二叉树的遍历循环一直觉得是自己的软肋, 在网上看到许多一些交叉, 总觉得只是囫囵吞枣, 强行记住, 却隐隐觉得自己没有真正理解其中的真谛
于是特地抽出时间对二叉树的遍历用代码实现了一遍, 找找手感。 二叉树的前序遍历, 和中序遍历整体感觉上都挺好实现的, 后续遍历由于需要两次返回节点, 颇有挑战性。
首先温习一下后续遍历的规则
public void Recurrence_travel(Bittree ptree)
{
if (ptree == null)
{
return;
}
Recurrence_travel(ptree.plefttree);
Recurrence_travel(ptree.prighttree);
Console.WriteLine(ptree.keyvalue.ToString());
}
二叉树的循环实现:
public void Loop_travel(Bittree ptree)
{
if (ptree == null)
{
return;
}
Poststack treelist = new Poststack();
int counts=-1;
while (ptree != null || treelist.Get_size() != 0)
{
while (ptree != null)
{
if (ptree.plefttree == null && ptree.prighttree == null)
{
Console.WriteLine(ptree.keyvalue.ToString());
break; // jump out first loop
}
if (ptree.plefttree != null)
{
treelist.Push(ptree);
ptree = ptree.plefttree;
continue; //ship into next loop
}
if (ptree.plefttree==null && ptree.prighttree != null)
{
treelist.Push(ptree);
break;
}
}
ptree = treelist.Pop(ref counts);
if (counts == 0) // first time to get back
{
ptree = ptree.prighttree; // turn right to travel
continue;
}
if (counts == 1) // second time to get back
{
Console.WriteLine(ptree.keyvalue.ToString());
ptree = null; // ensure it would not enter second loop
}
}
}
辅助堆栈:
class Poststack
{
// second paramter could be counts for the pop out
private Dictionary<Bittree, int> treedict=new Dictionary<Bittree, int>();
public Poststack()
{
}
public void Push(Bittree ptree)
{
if (ptree == null)
{
return;
}
treedict.Add(ptree, 0);
}
public Bittree Pop(ref int pcounts)
{
if (treedict.Count() ==0)
{
return null;
}
Bittree tptree = treedict.Last().Key;
pcounts = treedict.Last().Value;
if (pcounts == 0)
{
treedict.Remove(tptree);
treedict.Add(tptree, pcounts + 1);
return tptree;
}
if (pcounts == 1) // second travel
{
treedict.Remove(tptree);
return tptree;
}
return null;
}
public int Get_size()
{
return treedict.Count();
}
}