Balanced search tree๋ก ๋ง์ด ์ฐ์ด๋ Red-black tree (์ดํ RB tree)๋ฅผ C ์ธ์ด๋ก ๊ตฌํํ๋ ๊ณผ์ ์ ๋๋ค. ๊ตฌํํ๋ ์ถ์ ์๋ฃํ (ADT: abstract data type)์ ordered set, multiset ์ ๋๋ค.
๋ค์ ๊ธฐ๋ฅ๋ค์ ์ํํ ์ ์๋๋ก RB tree๋ฅผ ๊ตฌํํฉ๋๋ค.
-
tree =
new_tree()
: RB tree ๊ตฌ์กฐ์ฒด ์์ฑ- ์ฌ๋ฌ ๊ฐ์ tree๋ฅผ ์์ฑํ ์ ์์ด์ผ ํ๋ฉฐ ๊ฐ๊ฐ ๋ค๋ฅธ ๋ด์ฉ๋ค์ ์ ์ฅํ ์ ์์ด์ผ ํฉ๋๋ค.
-
delete_tree(tree)
: RB tree ๊ตฌ์กฐ์ฒด๊ฐ ์ฐจ์งํ๋ ๋ฉ๋ชจ๋ฆฌ ๋ฐํ- ํด๋น tree๊ฐ ์ฌ์ฉํ๋ ๋ฉ๋ชจ๋ฆฌ๋ฅผ ์ ๋ถ ๋ฐํํด์ผ ํฉ๋๋ค. (valgrind๋ก ๋ํ๋์ง ์์์ผ ํจ)
-
tree_insert(tree, key)
: key ์ถ๊ฐ- ๊ตฌํํ๋ ADT๊ฐ multiset์ด๋ฏ๋ก ์ด๋ฏธ ๊ฐ์ key์ ๊ฐ์ด ์กด์ฌํด๋ ํ๋ ๋ ์ถ๊ฐ ํฉ๋๋ค.
-
ptr =
tree_find(tree, key)
- RB tree๋ด์ ํด๋น key๊ฐ ์๋์ง ํ์ํ์ฌ ์์ผ๋ฉด ํด๋น node pointer ๋ฐํ
- ํด๋นํ๋ node๊ฐ ์์ผ๋ฉด NULL ๋ฐํ
-
tree_erase(tree, ptr)
: RB tree ๋ด๋ถ์ ptr๋ก ์ง์ ๋ node๋ฅผ ์ญ์ ํ๊ณ ๋ฉ๋ชจ๋ฆฌ ๋ฐํ -
ptr =
tree_min(tree)
: RB tree ์ค ์ต์ ๊ฐ์ ๊ฐ์ง node pointer ๋ฐํ -
ptr =
tree_max(tree)
: ์ต๋๊ฐ์ ๊ฐ์ง node pointer ๋ฐํ -
tree_to_array(tree, array, n)
- RB tree์ ๋ด์ฉ์ key ์์๋๋ก ์ฃผ์ด์ง array๋ก ๋ณํ
- array์ ํฌ๊ธฐ๋ n์ผ๋ก ์ฃผ์ด์ง๋ฉฐ tree์ ํฌ๊ธฐ๊ฐ n ๋ณด๋ค ํฐ ๊ฒฝ์ฐ์๋ ์์๋๋ก n๊ฐ ๊น์ง๋ง ๋ณํ
- array์ ๋ฉ๋ชจ๋ฆฌ ๊ณต๊ฐ์ ์ด ํจ์๋ฅผ ๋ถ๋ฅด๋ ์ชฝ์์ ์ค๋นํ๊ณ ๊ทธ ํฌ๊ธฐ๋ฅผ n์ผ๋ก ์๋ ค์ค๋๋ค.
src/rbtree.c
์ด์ธ์๋ ์์ ํ์ง ์๊ณ test๋ฅผ ํต๊ณผํด์ผ ํฉ๋๋ค.make test
๋ฅผ ์ํํ์ฌPassed All tests!
๋ผ๋ ๋ฉ์์ง๊ฐ ๋์ค๋ฉด ๋ชจ๋ test๋ฅผ ํต๊ณผํ ๊ฒ์ ๋๋ค.- Sentinel node๋ฅผ ์ฌ์ฉํ์ฌ ๊ตฌํํ๋ค๋ฉด
test/Makefile
์์CFLAGS
๋ณ์์-DSENTINEL
์ด ์ถ๊ฐ๋๋๋ก comment๋ฅผ ์ ๊ฑฐํด ์ค๋๋ค.
- ๋ณต์กํ ์๋ฃ๊ตฌ์กฐ(data structure)๋ฅผ ๊ตฌํํด ๋ด์ผ๋ก์จ ์์ ๊ฐ ์์น
- C ์ธ์ด, ํนํ ํฌ์ธํฐ(pointer)์ malloc, free ๋ฑ์ system call์ ์ต์ํด์ง.
- ๋์ ๋ฉ๋ชจ๋ฆฌ ํ ๋น(dynamic memory allocation)์ ์ง์ ์ฌ์ฉํด ๋ด์ผ๋ก์จ ๋์ ๋ฉ๋ชจ๋ฆฌ ํ ๋น์ ํ์์ฑ ์ฒด๊ฐ ๋ฐ data segment์ ๋ํ ์ดํด๋ ์์น
- ๊ณ ๊ธ ์ธ์ด์์ ๊ธฐ๋ณธ์ผ๋ก ์ ๊ณต๋๋ ์๋ฃ๊ตฌ์กฐ๊ฐ ์ธ๋ถ์ ์ผ๋ก๋ ์ด๋ป๊ฒ ๊ตฌํ๋์ด ์๋์ง ๊ฒฝํํจ์ผ๋ก์จ ๊ณ ๊ธ ์ธ์ด ์ฌ์ฉ์์๋ ํจ์จ์ฑ ๊ณ ๋ ค
- ์ํค๋ฐฑ๊ณผ: ๋ ๋-๋ธ๋ ํธ๋ฆฌ (์์ด)
- CLRS book (Introduction to Algorithms) 13์ฅ ๋ ๋ ๋ธ๋ ํธ๋ฆฌ - Sentinel node๋ฅผ ์ฌ์ฉํ ๊ตฌํ
- Wikipedia:๊ท ํ ์ด์ง ํธ๋ฆฌ์ ๊ตฌํ ๋ฐฉ๋ฒ๋ค