-
04/01 BinaryTree Preorder 순회 (Iterative) 복습자료구조/수업내용 2021. 4. 1. 09:57
순서
1. 이진트리, 노드 클래스 생성
2. 스택생성
루트를 스택에 넣음
3. 스택요소가 없을 때 까지 반복
스택에서 요소를 꺼내 출력
오른쪽이 null아니면 스택에 넣음
왼쪽이 null아니면 스택에 넣음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"); var A = tree.root; A.left = new BinaryNode("B"); A.right = new BinaryNode("C"); A.left.left = new BinaryNode("D"); A.left.right = new BinaryNode("E"); A.right.left = new BinaryNode("F"); tree.Print(); } } }
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 value; public BinaryNode left; public BinaryNode right; public BinaryNode(string value) { this.value = value; } } }
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 value) { root = new BinaryNode(value); } public void Print() { Stack<BinaryNode> stack = new Stack<BinaryNode>(); stack.Push(root); while(stack.Count > 0) { var temp = stack.Pop(); Console.Write(temp.value); if(temp.right != null) { stack.Push(temp.right); } if(temp.left != null) { stack.Push(temp.left); } } } } }
'자료구조 > 수업내용' 카테고리의 다른 글
04/01 수업내용 메모 (0) 2021.04.01 04/01 연결리스트로 구현한 BinaryTree & Preorder Traversal 복습 (0) 2021.04.01 03/31 수업내용 메모 (0) 2021.03.31 03/31 BinaryTree 전위, 중위, 후위 순회 출력 (0) 2021.03.31 03/31 BinaryTree 배열로 구현하기 (0) 2021.03.31