二叉树的遍历算法
有人提到树的层次遍历算法,我之前没听说过,于是找了资料看后,自己做了练习
using System;
using System.Collections.Generic;
using System.Text;
namespace 算法练习
{
class 两X树
{
public node root;
public string m_output = "";
public 两X树()
{
root = new node("A");
node B = new node("B");
root.left = B;
node C = new node("C");
root.right = C;
node D = new node("D");
B.right = D;
node E = new node("E");
C.left = E;
node F = new node("F");
C.right = F;
node G = new node("G");
D.left = G;
node H = new node("H");
D.right = H;
}
public void 先序(node n)
{
if (n != null)
{
m_output += " " + n.m_value;
先序(n.left);
先序(n.right);
}
}
public void 中序(node n)
{
if (n != null)
{
中序(n.left);
m_output += " " + n.m_value;
中序(n.right);
}
}
public void 后序(node n)
{
if (n != null)
{
后序(n.left);
后序(n.right);
m_output += " " + n.m_value;
}
}
List<List<node>> m_list = null;
public void 层次(node n)
{
m_list = new List<List<node>>();
层次(n, 0);
foreach (List<node> list in m_list)
{
foreach (node n_tmp in list)
m_output += " " + n_tmp.m_value;
}
}
public void 层次(node n, int dept )
{
if (n != null)
{
//m_output += " " + n.m_value;
if (m_list.Count <= dept)
m_list.Add( new List<node>());
m_list[dept].Add(n);
层次(n.left, dept + 1);
层次(n.right, dept + 1);
}
}
}
class node
{
public node left, right;
public string m_value;
public node(string value)
{
m_value = value;
}
}
}
using System.Collections.Generic;
using System.Text;
namespace 算法练习
{
class 两X树
{
public node root;
public string m_output = "";
public 两X树()
{
root = new node("A");
node B = new node("B");
root.left = B;
node C = new node("C");
root.right = C;
node D = new node("D");
B.right = D;
node E = new node("E");
C.left = E;
node F = new node("F");
C.right = F;
node G = new node("G");
D.left = G;
node H = new node("H");
D.right = H;
}
public void 先序(node n)
{
if (n != null)
{
m_output += " " + n.m_value;
先序(n.left);
先序(n.right);
}
}
public void 中序(node n)
{
if (n != null)
{
中序(n.left);
m_output += " " + n.m_value;
中序(n.right);
}
}
public void 后序(node n)
{
if (n != null)
{
后序(n.left);
后序(n.right);
m_output += " " + n.m_value;
}
}
List<List<node>> m_list = null;
public void 层次(node n)
{
m_list = new List<List<node>>();
层次(n, 0);
foreach (List<node> list in m_list)
{
foreach (node n_tmp in list)
m_output += " " + n_tmp.m_value;
}
}
public void 层次(node n, int dept )
{
if (n != null)
{
//m_output += " " + n.m_value;
if (m_list.Count <= dept)
m_list.Add( new List<node>());
m_list[dept].Add(n);
层次(n.left, dept + 1);
层次(n.right, dept + 1);
}
}
}
class node
{
public node left, right;
public string m_value;
public node(string value)
{
m_value = value;
}
}
}
调用方法:
private void button1_Click(object sender, EventArgs e)
{
两X树 xx = new 两X树();
xx.m_output = " 先序 :";
xx.先序( xx.root );
MessageBox.Show(xx.m_output);
xx.m_output = " 中序 :";
xx.中序(xx.root);
MessageBox.Show(xx.m_output);
xx.m_output = " 后序 :";
xx.后序(xx.root);
MessageBox.Show(xx.m_output);
xx.m_output = " 层次 :";
xx.层次(xx.root);
MessageBox.Show(xx.m_output);
}