자료구조/수업내용
03/31 BinaryTree 전위, 중위, 후위 순회 출력
박준희
2021. 3. 31. 17:22
Program.cs
using System;
namespace Study09
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Main");
new App();
}
}
}
App.cs
using System;
namespace Study09
{
public class App
{
//생성자
public App()
{
Console.WriteLine("App");
BinaryTree tree = new BinaryTree("A");
tree.root.left = new BinaryNode("B");
tree.root.right = new BinaryNode("C");
tree.root.left.left = new BinaryNode("D");
tree.root.left.right = new BinaryNode("E");
tree.root.right.left = new BinaryNode("F");
Console.WriteLine("\n전위 순회");
tree.PreorderTraversal();
Console.WriteLine("\n중위 순회");
tree.InorderTraversal();
Console.WriteLine("\n후위 순회");
tree.PostorderTraversal();
}
}
}
BinaryNode.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Study09
{
public class BinaryNode
{
public string data;
public BinaryNode left;
public BinaryNode right;
public BinaryNode(string data)
{
this.data = data;
}
}
}
BinaryTree.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Study09
{
public class BinaryTree
{
public BinaryNode root;
public BinaryTree(string data)
{
this.root = new BinaryNode(data);
}
//전위순회 (Preorder Traversal)
public void PreorderTraversal()
{
this.PreorderTraversalImple(this.root);
}
private void PreorderTraversalImple(BinaryNode node)
{
if (node == null) return;
Console.Write(node.data);
this.PreorderTraversalImple(node.left);
this.PreorderTraversalImple(node.right);
}
//중위 순회
public void InorderTraversal()
{
this.InorderTraversalImple(this.root);
}
private void InorderTraversalImple(BinaryNode node)
{
if (node == null) return;
this.InorderTraversalImple(node.left);
Console.Write("{0}", node.data);
this.InorderTraversalImple(node.right);
}
//후위 순회
public void PostorderTraversal()
{
this.PostorderTraversalImple(this.root);
}
private void PostorderTraversalImple(BinaryNode node)
{
if (node == null) return;
this.PostorderTraversalImple(node.left);
this.PostorderTraversalImple(node.right);
Console.Write("{0}", node.data);
}
}
}