3.7.2 In-Order Traversal(์ค‘์œ„ ์ˆœํšŒ)

2024. 2. 9. 02:25ใ†CS - Roadmap.sh/3. Common Algorithms

CS - 3. Common Algorithms - 3.7 Tree - 3.7.2 In-Order Traversal

In-Order Traversal

๐Ÿ’กIn-order traversal is a tree traversal algorithm that visits the left subtree, the root, and then the right subtree. This is the most common way to traverse a binary search tree. It is also used to create a sorted list of nodes in a binary search tree.

์ค‘์œ„ ์ˆœํšŒ(Inorder Traversal)์€ ์™ผ์ชฝ ํ•˜์œ„ ํŠธ๋ฆฌ, ๋ฃจํŠธ, ์˜ค๋ฅธ์ชฝ ํ•˜์œ„ ํŠธ๋ฆฌ๋ฅผ ์ฐจ๋ก€๋กœ ๋ฐฉ๋ฌธํ•˜๋Š” ํŠธ๋ฆฌ ํƒ์ƒ‰ ์•Œ๊ณ ๋ฆฌ์ฆ˜์ž…๋‹ˆ๋‹ค. ์ด์ง„ ๊ฒ€์ƒ‰ ํŠธ๋ฆฌ๋ฅผ ํƒ์ƒ‰ํ•˜๋Š” ๊ฐ€์žฅ ์ผ๋ฐ˜์ ์ธ ๋ฐฉ๋ฒ•์ž…๋‹ˆ๋‹ค. ๋˜ํ•œ ์ด์ง„ ๊ฒ€์ƒ‰ ํŠธ๋ฆฌ์—์„œ ์ •๋ ฌ๋œ ๋…ธ๋“œ ๋ชฉ๋ก์„ ๋งŒ๋“œ๋Š” ๋ฐ๋„ ์‚ฌ์šฉ๋ฉ๋‹ˆ๋‹ค.

 

 

In-Order Traversal์€ ์ด์ง„ ํŠธ๋ฆฌ๋ฅผ ์ˆœํšŒํ•˜๋Š” ๋ฐฉ๋ฒ• ์ค‘ ํ•˜๋‚˜๋กœ, ๊ฐ€์žฅ ๋ณดํŽธ์ ์œผ๋กœ ์‚ฌ์šฉ๋˜๋Š” ๋ฐฉ๋ฒ• ์ค‘ ํ•˜๋‚˜์ž…๋‹ˆ๋‹ค. ์ด ๋ฐฉ๋ฒ•์€ ๋…ธ๋“œ๋ฅผ '์™ผ์ชฝ ์ž์‹ - ๋ถ€๋ชจ - ์˜ค๋ฅธ์ชฝ ์ž์‹' ์ˆœ์„œ๋กœ ๋ฐฉ๋ฌธํ•˜๋Š” ๋ฐฉ์‹์„ ์˜๋ฏธํ•ฉ๋‹ˆ๋‹ค. ์ด ๋ฐฉ์‹์„ ์‚ฌ์šฉํ•˜๋ฉด ์ด์ง„ ํƒ์ƒ‰ ํŠธ๋ฆฌ์˜ ๊ฒฝ์šฐ ์˜ค๋ฆ„์ฐจ์ˆœ์œผ๋กœ ๋…ธ๋“œ๋ฅผ ์ถœ๋ ฅํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

 

 

In Python
class Node:
    def __init__(self, data, left=None, right=None):
        self.data = data
        self.left = left
        self.right = right

def in_order_traversal(node):
    if node is not None:
        in_order_traversal(node.left)
        print(node.data, end=' ')
        in_order_traversal(node.right)

๋…ธ๋“œ๋ฅผ ๋งŒ๋“ค๊ณ , ํ•จ์ˆ˜๋ฅผ ์„ค์ •ํ•ด์ค€๋‹ค.

 

์ด๋Ÿฐ ๊ทธ๋ž˜ํ”„๋ฅผ ์˜ˆ์‹œ๋กœ ์ค‘์œ„์ˆœ์ฐจ(inorder traversla)์„ ํ•ด๋ณด๊ฒ ์Šต๋‹ˆ๋‹ค.

 

 

 

 

ํ•จ์ˆ˜์˜ ๋™์ž‘ ๊ณผ์ •์€ ๋‹ค์Œ๊ณผ ๊ฐ™์Šต๋‹ˆ๋‹ค:

1. ๋ฃจํŠธ ๋…ธ๋“œ(1)์—์„œ ์‹œ์ž‘ํ•ฉ๋‹ˆ๋‹ค.
2. ๋ฃจํŠธ ๋…ธ๋“œ์˜ ์™ผ์ชฝ ์ž์‹๋…ธ๋“œ(2)๋กœ ์ด๋™ํ•ฉ๋‹ˆ๋‹ค.
3. ์ด๋™ํ•œ ๋…ธ๋“œ(2)๊ฐ€ ์™ผ์ชฝ ์ž์‹๋…ธ๋“œ(4)๋ฅผ ๊ฐ€์ง€๊ณ  ์žˆ์œผ๋ฏ€๋กœ, ๋‹ค์‹œ ์™ผ์ชฝ ์ž์‹๋…ธ๋“œ(4)๋กœ ์ด๋™ํ•ฉ๋‹ˆ๋‹ค.
4. ์ด๋™ํ•œ ๋…ธ๋“œ(4)๋Š” ๋” ์ด์ƒ ์™ผ์ชฝ ์ž์‹๋…ธ๋“œ๊ฐ€ ์—†์œผ๋ฏ€๋กœ, ์ด ๋…ธ๋“œ๋ฅผ ๋ฐฉ๋ฌธ(์ถœ๋ ฅ)ํ•ฉ๋‹ˆ๋‹ค.
5. ๋…ธ๋“œ(4)๋Š” ์˜ค๋ฅธ์ชฝ ์ž์‹๋…ธ๋“œ๋„ ์—†์œผ๋ฏ€๋กœ, ์ด ๋…ธ๋“œ์˜ ๋ถ€๋ชจ ๋…ธ๋“œ(2)๋กœ ๋Œ์•„๊ฐ€์„œ ์ด ๋…ธ๋“œ๋ฅผ ๋ฐฉ๋ฌธ(์ถœ๋ ฅ)ํ•ฉ๋‹ˆ๋‹ค.
6. ์ด์ œ ๋…ธ๋“œ(2)์˜ ์˜ค๋ฅธ์ชฝ ์ž์‹๋…ธ๋“œ(5)๋ฅผ ๋ฐฉ๋ฌธ(์ถœ๋ ฅ)ํ•ฉ๋‹ˆ๋‹ค.
7. ๋…ธ๋“œ(2)์˜ ๋ชจ๋“  ์ž์‹๋…ธ๋“œ๋ฅผ ๋ฐฉ๋ฌธํ–ˆ์œผ๋ฏ€๋กœ, ๋…ธ๋“œ(2)์˜ ๋ถ€๋ชจ ๋…ธ๋“œ(1)๋กœ ๋Œ์•„๊ฐ€์„œ ์ด ๋…ธ๋“œ๋ฅผ ๋ฐฉ๋ฌธ(์ถœ๋ ฅ)ํ•ฉ๋‹ˆ๋‹ค.
8. ๋งˆ์ง€๋ง‰์œผ๋กœ ๋…ธ๋“œ(1)์˜ ์˜ค๋ฅธ์ชฝ ์ž์‹๋…ธ๋“œ(3)๋ฅผ ๋ฐฉ๋ฌธ(์ถœ๋ ฅ)ํ•ฉ๋‹ˆ๋‹ค.

 

 

---(๋‚˜์ค‘์ˆ˜์ •)

์ด๊ฑฐ ์ด๋Ÿฌ๋ฉด ์žฌ๊ท€์ ์œผ๋กœ 1์—์„œ ํƒ€๊ณ ํƒ€๊ณ  ๋“ค์–ด๊ฐ€์„œ ์ œ์ผ ์•„๋ž˜์˜ ์ž์‹๋…ธ๋“œ์—์„œ ์‹œ์ž‘ํ•˜๋Š”๋ฐ

์ด๋Ÿฌ๋ฉด ์—ฐ์‚ฐ์„ ์ฒ˜์Œ 1๋ถ€ํ„ฐ pre-order ๋ณด๋‹ค ๊ณผ์ •์ด ๋” ์žˆ๋Š”๊ฒƒ ์•„๋‹Œ๊ฐ€??

์™œ ์“ฐ๋Š”๊ฑฐ์ง€?

728x90