完全二叉树(Complete Binary Tree):深度为k,有n个结点的二叉树当且仅当其每一个结点都与深度为k的满二叉树中编号从1到n的结点一一对应时,称为完全二叉树。
用了两个辅助方法,递归实现,C# codes as below:
class TreeNode
{
public TreeNode LeftSon { get; set; }
public TreeNode RightSon { get; set; }
public string Value { get; set; }
public TreeNode(string value = null, TreeNode leftSon=null, TreeNode rightSon=null)
{
this.LeftSon = leftSon;
this.RightSon = rightSon;
this.Value = value;
}
/// <summary>
/// Intergrate method DepthCount() and IfCompletedTree()
/// </summary>
/// <param name="rootNode"></param>
/// <param name="currentDepth"></param>
/// <param name="depth"></param>
/// <returns></returns>
public static bool IfCompletedTree(TreeNode rootNode)
{
int depth = DepthCount(rootNode);
if (rootNode == null)
{
return false;
}
else
{
return IfCompletedTree(rootNode.LeftSon, 2, depth) & IfCompletedTree(rootNode.RightSon, 2, depth);
}
}
/// <summary>
/// To get the depth of the tree
/// </summary>
/// <param name="rootNode"></param>
/// <returns></returns>
static int DepthCount(TreeNode rootNode)
{
if (rootNode == null)
{
return 0;
}
else if (rootNode.LeftSon == null && rootNode.RightSon == null)
{
return 1;
}
else
{
int leftDepth = DepthCount(rootNode.LeftSon);
int rightDepth = DepthCount(rootNode.RightSon);
return leftDepth > rightDepth ? leftDepth + 1 : rightDepth + 1;
}
}
/// <summary>
/// To judge if it is a completed tree
/// </summary>
/// <param name="rootNode"></param>
/// <param name="currentDepth"></param>
/// <param name="depth"></param>
/// <returns></returns>
static bool IfCompletedTree(TreeNode rootNode,int currentDepth,int depth)
{
if (rootNode == null)
{
if (currentDepth >= depth)
{
return true;
}
else
{
return false;
}
}
else
{
return IfCompletedTree(rootNode.LeftSon, currentDepth + 1, depth) & IfCompletedTree(rootNode.RightSon, currentDepth + 1, depth);
}
}
}