有人提到树的层次遍历算法,我之前没听说过,于是找了资料看后,自己做了练习
usingSystem;
usingSystem.Collections.Generic;
usingSystem.Text;
namespace算法练习
{
class两X树
{
publicnoderoot;
publicstringm_output="";
public两X树()
{
root=newnode("A");
nodeB=newnode("B");
root.left=B;
nodeC=newnode("C");
root.right=C;
nodeD=newnode("D");
B.right=D;
nodeE=newnode("E");
C.left=E;
nodeF=newnode("F");
C.right=F;
nodeG=newnode("G");
D.left=G;
nodeH=newnode("H");
D.right=H;
}
publicvoid先序(noden)
{
if(n!=null)
{
m_output+=""+n.m_value;
先序(n.left);
先序(n.right);
}
}
publicvoid中序(noden)
{
if(n!=null)
{
中序(n.left);
m_output+=""+n.m_value;
中序(n.right);
}
}
publicvoid后序(noden)
{
if(n!=null)
{
后序(n.left);
后序(n.right);
m_output+=""+n.m_value;
}
}
List<List<node>>m_list=null;
publicvoid层次(noden)
{
m_list=newList<List<node>>();
层次(n,0);
foreach(List<node>listinm_list)
{
foreach(noden_tmpinlist)
m_output+=""+n_tmp.m_value;
}
}
publicvoid层次(noden,intdept)
{
if(n!=null)
{
//m_output+=""+n.m_value;
if(m_list.Count<=dept)
m_list.Add(newList<node>());
m_list[dept].Add(n);
层次(n.left,dept+1);
层次(n.right,dept+1);
}
}
}
classnode
{
publicnodeleft,right;
publicstringm_value;
publicnode(stringvalue)
{
m_value=value;
}
}
}
调用方法:
长按二维码向我转账
受苹果公司新规定影响,微信 iOS 版的赞赏功能被关闭,可通过二维码转账支持公众号。
阅读
好看
已推荐到看一看
你的朋友可以在“发现”-“看一看”看到你认为好看的文章。
取消
分享想法到看一看
确定
最多200字,当前共字