0401 연결리스트를 사용해 이진트리 만들고 Postorder Traversal (Iterative) 복습
2021. 4. 1. 14:39ㆍC#/자료구조
public class BinaryTree
{
public BinaryTreeNode root;
public BinaryTree(string data)
{
this.root = new BinaryTreeNode(data);
}
public void PostorderIterative()
{
//스택을 만든다.
var stack = new Stack<BinaryTreeNode>();
//변수에 루트를 넣는다.
var node = this.root;
//왼쪽 끝까지 오른쪽 노드와 루트 노드를 넣는다.
while (node != null)
{
if (node.right != null)
{
stack.Push(node.right);
}
stack.Push(node);
node = node.left;
}
//스택에 요소가 있으면 반복
while (stack.Count > 0)
{
//꺼낸다.
node = stack.Pop();
//노드를 꺼내어 스택의 top과 비교
if (node.right != null && stack.Count > 0 && node.right == stack.Peek())
{
// 같다면 꺼낸다
var right = stack.Pop();
//루트를 넣는다.
stack.Push(node);
node = node.right;
//마지막 왼쪽 노드가 없을 때까지 반복
while (node != null) {
//우측 노드 넣고 루트 넣고
if (node.right != null)
{
stack.Push(node.right);
}
stack.Push(node);
//왼쪽 노드 확인
node = node.left;
}
}
else
{
//틀리다면
//출력한다.
Console.WriteLine("{0}", node.data);
}
}
}
}
public class App
{
public App()
{
BinaryTree tree = new BinaryTree("A");
tree.root.left = new BinaryTreeNode("B");
tree.root.right = new BinaryTreeNode("C");
tree.root.left.left = new BinaryTreeNode("D");
tree.root.left.right = new BinaryTreeNode("E");
tree.root.right.left = new BinaryTreeNode("F");
tree.PostorderIterative();
}
}
'C# > 자료구조' 카테고리의 다른 글
0402 이진 탐색 트리 재귀 함수로 중위순회 (0) | 2021.04.02 |
---|---|
0401 이진탐색트리Binary Search Tree (0) | 2021.04.01 |
0401 연결리스트로 이진트리 만들고 중위순회 하기 (Iterative방식) 복습 (0) | 2021.04.01 |
0401 연결리스트로 구현한 이진트리 InorderTraversal (Iterative) 복습 (0) | 2021.04.01 |
0401 연결리스트로 구현한 이진트리 Preorder Traversal (Iterative) 복습 (0) | 2021.04.01 |