1.需求
假装有图,因为图太大传不上去。
tree 的初始值(1(2,3(4,5(69))8)))
2.具体实现
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
/// <summary>
/// 设计树结构
/// </summary>
public sealed class Tree
{
private int _NodeValue;//节点值
private Tree _LeftChlidNode;//左节点
private Tree _RightChlidNode;//右节点
/// <summary>
/// 获取节点值
/// </summary>
/// <returns></returns>
public int GetNodeValue()
{
return _NodeValue;
}
/// <summary>
/// 设置节点值
/// </summary>
/// <param name="value"></param>
public void SetNodeValue(int value)
{
_NodeValue = value;
}
/// <summary>
/// 获取左节点
/// </summary>
/// <returns></returns>
public Tree GetLeftChlid()
{
if (_LeftChlidNode == null)
_LeftChlidNode = new Tree();
return _LeftChlidNode;
}
/// <summary>
/// 获取右节点
/// </summary>
/// <returns></returns>
public Tree GetRightChild()
{
if (_RightChlidNode == null)
_RightChlidNode = new Tree();
return _RightChlidNode;
}
}
/// <summary>
/// 测试
/// </summary>
public sealed class test
{
List<int> result = new List<int>();
/// <summary>
/// 树转list集合
/// </summary>
/// <param name="tree">头结点</param>
/// <returns></returns>
public List<int> TreeConvertToList(Tree tree)
{
if (tree == null)
return null;
Tree leftnode = tree.GetLeftChlid();
Tree rightnode = tree.GetRightChild();
if (leftnode.GetNodeValue() != 0)
{
result.Add(leftnode.GetNodeValue());
TreeConvertToList(leftnode);
}
if (rightnode.GetNodeValue() != 0)
{
result.Add(rightnode.GetNodeValue());
TreeConvertToList(rightnode);
}
return result;
}
/// <summary>
/// 初始化树
/// </summary>
/// <param name="tree"></param>
/// <returns></returns>
public Tree InialTree( Tree tree)
{
Tree p0_0 = tree.GetLeftChlid();
p0_0.SetNodeValue(1);
Tree p0_1 = tree.GetRightChild();
p0_1.SetNodeValue(8);
Tree a1 = p0_0.GetLeftChlid();
a1.SetNodeValue(2);
Tree a2 = p0_0.GetRightChild();
a2.SetNodeValue(3);
Tree b1 = a2.GetLeftChlid();
b1.SetNodeValue(4);
Tree b2 = a2.GetRightChild();
b2.SetNodeValue(5);
Tree c1 = b2.GetRightChild();
c1.SetNodeValue(69);
return tree;
}
}
}
3.调用显示
class Program
{
static void Main(string[] args)
{
test test = new test();
Tree Roottree = new Tree();//根部
Roottree= test.InialTree( Roottree);
List<int> result = test.TreeConvertToList(Roottree);
//循环输出
foreach (int item in result)
{
Console.Write(item.ToString());
Console.Write(",");
}
Console.Read();
}
}