代码下载地址:
链接: https://pan.baidu.com/s/1bpHayoJ 密码: k6su
接下来看主要代码
1、先构建二叉树的类
public class Node
{
public int data; //自己本身值
public Node left; //左结点
public Node right; //右结点
public Node()
{
}
public Node(int data, Node left, Node right)
{
this.data = data;
this.left = left;
this.right = right;
}
public int getData()
{
return data;
}
public void setData(int data)
{
this.data = data;
}
public Node getLeft()
{
return left;
}
public void setLeft(Node left)
{
this.left = left;
}
public Node getRight()
{
return right;
}
public void setRight(Node right)
{
this.right = right;
}
}
2、然后构建二叉树
public static List<Node> CreateTree(int[] array)
{
List<Node> list = new List<Node>();
for (int i = ; i < array.Length; i++)
{
Node node = new Node(array[i], null, null); //创建结点,每一个结点的左结点和右结点为null
list.Add(node); // list中存着每一个结点
}
// 构建二叉树
if (list.Count > )
{
for (int i = ; i < array.Length / - ; i++)
{ // i表示的是根节点的索引,从0开始
if (list[ * i + ] != null)
{
// 左结点
list[i].left = list[ * i + ];
}
if (list[ * i + ] != null)
{
// 右结点
list[i].right = list[ * i + ];
}
}
// 判断最后一个根结点:因为最后一个根结点可能没有右结点,所以单独拿出来处理
int lastIndex = array.Length / - ;
// 左结点
list[lastIndex].left = list[lastIndex * + ];
// 右结点,如果数组的长度为奇数才有右结点
if (array.Length % == )
{
list[lastIndex].right = list[lastIndex * + ];
}
}
return list;
}
3、接下来打印二叉树
public static void PrintTree(Node node, int Layer)
{
if (node == null) { return; }
PrintTree(node.right, Layer + );
for (int i = ; i < Layer; i++)
{
Console.Write(" ");
}
Console.WriteLine(node.data);
PrintTree(node.left, Layer + );
}
4、最后是调用
static void Main(string[] args)
{
int[] array = { , , , , , , , ,
,,, , , , , , , , };
List<Node> list = TwoForkedTree.CreateTree(array);
TwoForkedTree.PrintTree(list[], );
Console.ReadLine();
}
运行之后的结果是