尝试了一下用C#写了一下二叉树的相关算法:
代码
#region 获取二叉树深度
static int z, d = 0; //z用于记录遍历到某节点时的深度,d用于记录最大深度
static int GetTreeDep(TreeNode node)
{
z++;
if (d < z)
d = z;
if (node.leftNode != null)
{
GetTreeDep(node.leftNode);
z--;
}
if (node.rightNode != null)
{
GetTreeDep(node.rightNode);
z--;
}
return d;
}
#endregion
#region 分层遍历二叉树
static ArrayList al = new ArrayList();
static ArrayList RecursiveTreeByLevel(TreeNode node)
{
k++;
if (al.Count < k)
{
al.Add(node.nodeName);
}
else
{
al[k - 1] += node.nodeName;
}
if (node.leftNode != null)
{
RecursiveTreeByLevel(node.leftNode);
k--;
}
if (node.rightNode != null)
{
RecursiveTreeByLevel(node.rightNode);
k--;
}
return al;
}
#endregion
static int z, d = 0; //z用于记录遍历到某节点时的深度,d用于记录最大深度
static int GetTreeDep(TreeNode node)
{
z++;
if (d < z)
d = z;
if (node.leftNode != null)
{
GetTreeDep(node.leftNode);
z--;
}
if (node.rightNode != null)
{
GetTreeDep(node.rightNode);
z--;
}
return d;
}
#endregion
#region 分层遍历二叉树
static ArrayList al = new ArrayList();
static ArrayList RecursiveTreeByLevel(TreeNode node)
{
k++;
if (al.Count < k)
{
al.Add(node.nodeName);
}
else
{
al[k - 1] += node.nodeName;
}
if (node.leftNode != null)
{
RecursiveTreeByLevel(node.leftNode);
k--;
}
if (node.rightNode != null)
{
RecursiveTreeByLevel(node.rightNode);
k--;
}
return al;
}
#endregion