ํ‹ฐ์Šคํ† ๋ฆฌ ๋ทฐ

728x90
๋ฐ˜์‘ํ˜•

Recursion?

์žฌ๊ท€๋Š” ํŠน์ • ํ•จ์ˆ˜ ๋‚ด์—์„œ ํ•จ์ˆ˜ ์ž์‹ ์„ ๋‹ค์‹œ ํ˜ธ์ถœํ•˜๋Š” ๊ฒƒ์„ ์˜๋ฏธํ•œ๋‹ค. ์žฌ๊ท€๋Š” Stack์˜ ํŠน์„ฑ์„ ๊ทธ๋Œ€๋กœ ๋ฐ˜์˜ํ•˜์—ฌ, ๊ฐ€์žฅ ์ตœ๊ทผ์— ํ˜ธ์ถœ๋œ ํ•จ์ˆ˜ ๋ถ€ํ„ฐ ์ฒ˜๋ฆฌ๋˜๋Š” ๋ฐฉ์‹์œผ๋กœ ์ง„ํ–‰๋œ๋‹ค. ์žฌ๊ท€๋ฅผ ์ž˜ ๋‹ค๋ฃฐ ์ˆ˜ ์žˆ๋‹ค๋ฉด DFS์™€ ๋ฐฑํŠธ๋ž˜ํ‚น, ํŠธ๋ฆฌ ํƒ์ƒ‰๊ณผ ๊ฐ™์€ ๋ฌธ์ œ๋ฅผ ํ•ด๊ฒฐ ํ• ๋•Œ ํšจ์œจ์ ์œผ๋กœ ์ ‘๊ทผํ•  ์ˆ˜ ์žˆ๊ฒŒ ๋œ๋‹ค.

 


์ด์ง„ ํŠธ๋ฆฌ ์ˆœํšŒ

Figure 1. Depth 3์˜ ์ด์ง„ ํŠธ๋ฆฌ

๊ทธ๋ฆผ 1๊ณผ ๊ฐ™์€ ์ด์ง„ ํŠธ๋ฆฌ๊ฐ€ ์žˆ์„ ๊ฒฝ์šฐ, 3๊ฐ€์ง€ ๋ฐฉ์‹์œผ๋กœ ํŠธ๋ฆฌ๋ฅผ ์ˆœํšŒํ•  ์ˆ˜ ์žˆ๋‹ค. ์ฒซ ๋ฒˆ์งธ๋Š” ์ „์œ„ ์ˆœํšŒ๋กœ 1-2-4-5-3-6-7 ์ˆœ์„œ๋กœ ํŠธ๋ฆฌ๋ฅผ ์ˆœํšŒํ•œ๋‹ค. ๋‘ ๋ฒˆ์งธ๋Š” ์ค‘์œ„ ์ˆœํšŒ๋กœ 4-2-5-1-6-3-7 ์ˆœ์„œ๋กœ ํŠธ๋ฆฌ๋ฅผ ์ˆœํšŒ ํ•œ๋‹ค. ๋งˆ์ง€๋ง‰์œผ๋กœ ํ›„์œ„์ˆœํšŒ๋Š” 4-5-2-6-7-3-1๋กœ ์ˆœํšŒํ•œ๋‹ค. ํŠธ๋ฆฌ๋ฅผ ์ˆœํšŒํ•˜๋Š” ๊ฒƒ์€ ์žฌ๊ท€ ํ˜ธ์ถœ์„ ํ†ตํ•ด์„œ ๊ตฌํ˜„ ํ•  ์ˆ˜ ์žˆ๋‹ค.

 

 

Simple Tree Travel

def tree_travel(num, order):
    if num > 7:
        return
    else:
        if order == 'pre':
            print(num, end=' ')
            tree_travel(num * 2, order)
            tree_travel((num * 2) + 1, order)
        elif order == 'in':
            tree_travel(num * 2, order)
            print(num, end=' ')
            tree_travel((num * 2) + 1, order)
        else:
            tree_travel(num * 2, order)
            tree_travel((num * 2) + 1, order)
            print(num, end=' ')


tree_travel(1, 'pre')
print()
tree_travel(1, 'in')
print()
tree_travel(1, 'post')
  • ์ „์œ„ ์ˆœํšŒ(pre)์ธ ๊ฒฝ์šฐ, ์ ‘๊ทผํ•œ ๋…ธ๋“œ - left child - right child ์ˆœ์œผ๋กœ ์ฒ˜๋ฆฌํ•œ๋‹ค.
  • ์ค‘์œ„ ์ˆœํšŒ(in)์˜ ๊ฒฝ์šฐ, left child - ์ ‘๊ทผํ•œ ๋…ธ๋“œ - right child ์ˆœ์œผ๋กœ ์ฒ˜๋ฆฌํ•œ๋‹ค.
  • ํ›„์œ„ ์ˆœํšŒ(post)์˜ ๊ฒฝ์šฐ left child - right child - ์ ‘๊ทผํ•œ ๋…ธ๋“œ ์ˆœ์œผ๋กœ ์ฒ˜๋ฆฌํ•œ๋‹ค.
  • ์‹คํ–‰ ๊ฒฐ๊ณผ๋Š” ์œ„์˜ ์„ค๋ช…๊ณผ ๋™์ผํ•œ ๋ฐฉ์‹์œผ๋กœ ํ˜ธ์ถœ๋œ๋‹ค.
728x90
๋ฐ˜์‘ํ˜•
๋Œ“๊ธ€
๊ธ€ ๋ณด๊ด€ํ•จ
์ตœ๊ทผ์— ์˜ฌ๋ผ์˜จ ๊ธ€
์ตœ๊ทผ์— ๋‹ฌ๋ฆฐ ๋Œ“๊ธ€