Left Child Right Sibiling (왼쪽 자식 노드, 오른쪽 형제 노드)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Tree
{
class Tree
{
public class Node
{
public string data;
public Node left;
public Node right;
//생성자
public Node(string data)
{
this.data = data;
}
}
public Node root;
//생성자
public Tree(string data)
{
this.root = new Node(data);
}
//자식 노드 추가
public Node AddChild(Node parent, string data)
{
if (parent == null) return null;
Node child = new Node(data);
if(parent.left== null)
{
parent.left = child;
}
else
{
var node = parent.left;
while(node.right != null)
{
node = node.right;
}
node.right = child;
}
return child;
}
//형제 노드 추가
public Node AddSibiling(Node node, string data)
{
if (node == null) return null;
while(node.right != null)
{
node = node.right;
}
var sibiling = new Node(data);
node.right = sibiling;
return sibiling;
}
//레벨순으로 트리 노드 출력
public void PrintLevelOrder()
{
var q = new Queue<Node>();
q.Enqueue(this.root);
while (q.Count > 0)
{
var node = q.Dequeue();
while (node != null)
{
Console.Write("{0} ", node.data);
if(node.left != null)
{
q.Enqueue(node.left);
}
node = node.right;
}
}
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Tree
{
class App
{
//생성자
public App()
{
Tree tree = new Tree("A");
var A = tree.root;
var B = tree.AddChild(A, "B");
tree.AddChild(A, "C");
var D = tree.AddSibiling(B, "D");
tree.AddChild(B, "E");
tree.AddChild(B, "F");
tree.AddChild(D, "G");
tree.PrintLevelOrder();
}
}
}
'c# > 수업 내용' 카테고리의 다른 글
유니티 (0) | 2023.01.26 |
---|---|
인벤토리 만들기 (0) | 2023.01.16 |
변하는 데이터 만들기 연습 (0) | 2023.01.15 |
변하지 않는 데이터 만들기 연습 2 (Mission, Item) (0) | 2023.01.13 |
230113 (0) | 2023.01.13 |