遍历二叉树获取数据

发布于:2021-06-14 22:22:31

2019独角兽企业重金招聘Python工程师标准>>>



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
{
///


/// 设计树结构
///

public sealed class Tree
{
private int _NodeValue;//节点值
private Tree _LeftChlidNode;//左节点
private Tree _RightChlidNode;//右节点
///
/// 获取节点值
///

///
public int GetNodeValue()
{
return _NodeValue;
}
///
/// 设置节点值
///

///
public void SetNodeValue(int value)
{
_NodeValue = value;
}
///
/// 获取左节点
///

///
public Tree GetLeftChlid()
{
if (_LeftChlidNode == null)
_LeftChlidNode = new Tree();
return _LeftChlidNode;
}
///
/// 获取右节点
///

///
public Tree GetRightChild()
{
if (_RightChlidNode == null)
_RightChlidNode = new Tree();
return _RightChlidNode;
}
}

///
/// 测试
///

public sealed class test
{
List result = new List();
///
/// 树转list集合
///

/// 头结点
///
public List 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;
}

///
/// 初始化树
///

///
///
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 result = test.TreeConvertToList(Roottree);
//循环输出
foreach (int item in result)
{
Console.Write(item.ToString());
Console.Write(",");

}
Console.Read();
}
}

?








转载于:https://my.oschina.net/RabbitXiao/blog/788173

相关推荐

最新更新

猜你喜欢