统计二叉树中叶子结点的数目

如题,C# codes 递归如下:

class Program

{

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(leafNumberCount(node9));

Console.ReadKey();

}

static int leafNumberCount(TreeNode theTree)

{

if (theTree == null)

{

return 0;

}

if (theTree.LeftSon == null && theTree.RightSon == null)

{

return 1;

}

int count = 0;

if (theTree.LeftSon != null)

{

count += leafNumberCount(theTree.LeftSon);

}

if (theTree.RightSon != null)

{

count += leafNumberCount(theTree.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 result:

4

你可能感兴趣的:(二叉树)