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