二叉树结点类:
插入代码的页面打不开,所以直接这样粘代码了 :(
public class Node
{
private Node left;
private Node right;
private int value;
public Node(Node left, Node right, int value)
{
this.left = left;
this.right = right;
this.value = value;
}
public Node(int value)
{
this.value = value;
}
public Node getLeftNode() { return left; }
public Node getRightNode() { return right; }
public int getValue() { return value; }
/// <summary>
/// 查找某一节点
/// </summary>
/// <param name="node">根节点</param>
/// <param name="value">要查找的值</param>
/// <returns></returns>
public Node findNode(Node root, int value)
{
if (root == null)
{
return null;
}
if (root.getValue() == value)
{
return root;
}
if (value < root.getValue())
{
findNode(root.getLeftNode(), value);
}
else
{
findNode(root.getRightNode(), value);
}
return null;
}
/// <summary>
/// 先根遍历
/// </summary>
/// <param name="root"></param>
public static void PreOrder(Node root)
{
if (root != null)
{
Console.WriteLine(root.getValue());
PreOrder(root.getLeftNode());
PreOrder(root.getRightNode());
}
}
/// <summary>
/// 后根遍历
/// </summary>
/// <param name="root"></param>
public static void AfterOrder(Node root)
{
if (root != null)
{
AfterOrder(root.getLeftNode());
AfterOrder(root.getRightNode());
Console.WriteLine(root.getValue());
}
}
/// <summary>
/// 中序遍历二叉树
/// </summary>
/// <param name="root"></param>
public static void MidOrder(Node root)
{
if (root != null)
{
MidOrder(root.getLeftNode());
Console.WriteLine(root.getValue());
MidOrder(root.getRightNode());
}
}
public static int leafNodeCount = 0;
public static void count_leafNode(Node root)
{
if (root == null)
{
return;
}
if (root.getLeftNode() == null && root.getRightNode() == null)
{
Console.WriteLine("叶子节点" + leafNodeCount.ToString() + "的值为:" + root.getValue());
leafNodeCount++;
}
else
{
count_leafNode(root.getLeftNode());
count_leafNode(root.getRightNode());
}
}
}
为了简便起见,将遍历等相关方法都写在了该节点中。
以下是主程序调用:
public void showMain()
{
//构建二叉树
Node[] node=new Node[8];
node[4] = new Node(5);
node[5] = new Node(6);
node[6] = new Node(7);
node[3] = new Node(node[6], node[7], 3);
node[2] = new Node(node[4], node[5], 2);
node[1] = new Node(node[3], null, 2);
node[0] = new Node(node[1], node[2], 0);
Console.WriteLine("后根遍历:");
Node.AfterOrder(node[0]);
Console.WriteLine("先根遍历:");
Node.PreOrder(node[0]);
Console.WriteLine("中根遍历:");
Node.MidOrder(node[0]);
Console.WriteLine("共有叶子节点个数为:");
Node.count_leafNode(node[0]);
Console.WriteLine(Node.leafNodeCount);
Console.Read();
}