二叉树示例:
二叉树结构,其中parent为父节点,child1为左孩子,child2为右孩子,data为该节点存放的数据。
1 class TreeNode
2 {
3 public TreeNode parent = null;
4 public TreeNode child1 = null;
5 public TreeNode child2 = null;
6
7 public object data = null;
8 }
2 {
3 public TreeNode parent = null;
4 public TreeNode child1 = null;
5 public TreeNode child2 = null;
6
7 public object data = null;
8 }
创建二叉树
1
static TreeNode CreateBinaryTree()
2
{
3
TreeNode[] node = new TreeNode[6];
4
5
for (int i = 0; i < 6; i++)
6
{
7
node[i] = new TreeNode();
8
node[i].data = i;
9
}
10
11
node[0].child1 = node[1];
12
node[0].child2 = node[2];
13
node[1].parent = node[2].parent = node[0];
14
15
node[1].child1 = node[3];
16
node[1].child2 = node[4];
17
node[3].parent = node[4].parent = node[1];
18
19
return node[0];
20
}

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

显示二叉树(后序遍历,即先访问左孩子,再访问右孩子,最后访问根)
1
static void DispalyBinaryTree(TreeNode root)
2
{
3
4
if (root.child1 == null && root.child2 == null)
5
{
6
Console.WriteLine(root.data);
7
}
8
else
9
{
10
DispalyBinaryTree(root.child1);
11
DispalyBinaryTree(root.child2);
12
Console.WriteLine(root.data);
13
}
14
}

2

3

4

5

6

7

8

9

10

11

12

13

14

使用
1 TreeNode n = CreateBinaryTree();
2 DispalyBinaryTree(n);
2 DispalyBinaryTree(n);