概述
递归,C#如下:
static void Main(string[] args)
{
TreeNode node1 = new TreeNode("1");
TreeNode node2 = new TreeNode("2");
TreeNode node3 = new TreeNode("3");
TreeNode node4 = new TreeNode("4");
TreeNode node5 = new TreeNode("5",node1,node2);
TreeNode node6 = new TreeNode("6", node5, node3);
TreeNode node7 = new TreeNode("7", node6);
TreeNode node8 = new TreeNode("8", node4, node7);
TreeNode node9 = new TreeNode("9", null, node8);
Console.WriteLine(branchNodeCount(node9));
Console.ReadKey();
}
static int branchNodeCount(TreeNode rootNode)
{
if (rootNode == null)
{
return 0;
}
else if (rootNode.LeftSon == null && rootNode.RightSon == null)
{
return 0;
}
else
{
int count = 1;
if (rootNode.LeftSon != null)
{
count += branchNodeCount(rootNode.LeftSon);
}
if (rootNode.RightSon != null)
{
count += branchNodeCount(rootNode.RightSon);
}
return count;
}
}
}
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;
}
}
output:
5
最后
以上就是粗暴月光为你收集整理的统计二叉树中分支节点的数目的全部内容,希望文章能够帮你解决统计二叉树中分支节点的数目所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复