判断给定的二叉树是否为完全二叉树

完全二叉树(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);

}

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值