数据结构(二叉树)C#描述

本文介绍了一种二叉树的实现方式,包括节点结构定义、二叉树的创建过程及后序遍历方法。通过示例代码展示了如何创建一个包含六个节点的二叉树,并采用递归方式实现后序遍历。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

二叉树示例:

二叉树结构,其中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 }

 
创建二叉树

 1static TreeNode CreateBinaryTree()
 2ExpandedBlockStart.gifContractedBlock.gif{
 3    TreeNode[] node = new TreeNode[6];
 4
 5    for (int i = 0; i < 6; i++)
 6ExpandedSubBlockStart.gifContractedSubBlock.gif    {
 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}


显示二叉树(后序遍历,即先访问左孩子,再访问右孩子,最后访问根)

 1static void DispalyBinaryTree(TreeNode root)
 2ExpandedBlockStart.gifContractedBlock.gif{
 3
 4    if (root.child1 == null && root.child2 == null)
 5ExpandedSubBlockStart.gifContractedSubBlock.gif    {
 6        Console.WriteLine(root.data);
 7    }

 8    else
 9ExpandedSubBlockStart.gifContractedSubBlock.gif    {
10        DispalyBinaryTree(root.child1);
11        DispalyBinaryTree(root.child2);
12        Console.WriteLine(root.data);
13    }

14}


使用

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


转载于:https://www.cnblogs.com/iPeterRex/archive/2008/11/23/1339482.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值