[4์ฃผ์ฐจ] Tree

Chenยท2024๋…„ 5์›” 18์ผ

Data Structure

๋ชฉ๋ก ๋ณด๊ธฐ
5/10
post-thumbnail

1. Tree ๊ฐœ๋…

Node๋กœ ์ด๋ฃจ์–ด์ง„ ์ž๋ฃŒ๊ตฌ์กฐ๋กœ, ์Šคํƒ/ํ์™€ ๊ฐ™์€ ์„ ํ˜• ๊ตฌ์กฐ(Linear)๊ฐ€ ์•„๋‹Œ ๋น„์„ ํ˜•(Non-linear) ๊ตฌ์กฐ

ํŠธ๋ฆฌ = Node์™€ Link์˜ ์ง‘ํ•ฉ

(= ํ•˜๋‚˜์˜ ์ž๋ฃŒ ๋’ค์— ์—ฌ๋Ÿฌ ๊ฐœ์˜ ์ž๋ฃŒ๊ฐ€ ์กด์žฌํ•  ์ˆ˜ ์žˆ๋Š” ํ˜•ํƒœ)

์ž๋ฃŒ๋“ค๊ฐ„์˜ ์•ž, ๋’ค ๊ด€๊ณ„๊ฐ€ 1: n ๋˜๋Š” n:n์˜ ๊ด€๊ณ„๋ฅผ ๋‚˜ํƒ€๋‚ด๋ฉฐ, ๊ณ„์ธต์  ๊ตฌ์กฐ๋ฅผ ๋‚˜ํƒ€๋‚ด๊ธฐ์— ์ ์ ˆ
ํŒจ๋“œ ์žˆ์œผ๋ฉด ๋ญํ•˜๋‚˜... ๊ท€์ฐจ๋Š”๋ฐ...


์—ฌํŠผ... HTML, React DOM์„ ๋– ์˜ฌ๋ ค๋ณด๋ผ

<html>
	<head>
    	<body>
        	<div></div>
			<div></div>
        </body>
    </head>
</html>

<html> ์ด root Node๊ณ 

root๊ฐ€ ์—†๋”๋ผ๋„ ์ž„์˜๋กœ root๋ฅผ ๋งŒ๋“ค์–ด์ฃผ์–ด ํŠธ๋ฆฌ๋ฅผ ์•Œ๊ณ ๋ฆฌ์ฆ˜์— ํ™œ์šฉํ•  ์ˆ˜ ์žˆ์Œ
(or ์ตœ์ข…์ ์œผ๋กœ <> </>๋กœ wrapper์„ ๋งŒ๋“ค๋ฉด ๋จ)

์ผ์ƒ์ƒํ™œ/ํ”„๋กœ๊ทธ๋žจ์—์„œ ์ •๋ง ๋งŽ์ด ์“ฐ์ด๋Š” ๊ตฌ์กฐ

Tree๋Š” ๊ฐ€์ง€์— ๊ฐœ์ˆ˜ ์ œํ•œ์ด ์—†์Œ
=> ๋„ˆ๋ฌด ๋งŽ์€ ๊ฐ€์ง€๊ฐ€ ๋‚˜์˜ค๋ฉด ์•Œ๊ณ ๋ฆฌ์ฆ˜์œผ๋กœ ํ™œ์šฉํ•˜๊ธฐ ์–ด๋ ค์›€
=> ๊ฐ€์ง€ ๊ฐœ์ˆ˜์— ์ œํ•œ์„ ์คŒ
ex. ์ด์ง„ ํŠธ๋ฆฌ binary tree (๊ฐ€์ง€ 0~2๊ฐœ) => (๊ฒ€์ƒ‰/์ •๋ ฌ)

๊ฐ๊ฐ์˜ Node ๋งˆ๋‹ค children ๊ฐœ์ˆ˜๊ฐ€ ๋‹ค ๋‹ฌ๋ผ์„œ ์•Œ๊ณ ๋ฆฌ์ฆ˜์„ ํ†ต์ผ๋˜๊ฒŒ ์ ์šฉํ•˜๊ธฐ ์–ด๋ ค์›€

=> ๋‹จ์ˆœ Tree๊ตฌ์กฐ์—์„œ๋Š” ์‹ ๋‚˜๊ฒŒ push()ํ•˜๋Š” ๋А๋‚Œ์ด๋ผ ํŠน๋ณ„ํ•œ ๊ฒŒ ์—†์Œ..ใ…‹ใ…‹
=> ๊ทธ๋ž˜์„œ ๋ ˆ๋“œ๋ธ”๋ž™ํŠธ๋ฆฌ, AVL ํŠธ๋ฆฌ, ์ด์ง„ ํŠธ๋ฆฌ, ์ด์ง„ ํƒ์ƒ‰ ํŠธ๋ฆฌ ๋“ฑ ์—ฌ๋Ÿฌ ์ข…๋ฅ˜๊ฐ€ ์žˆ์Œ

์šฉ์–ด

	Root
	Edge(๋งํฌ)

	Leaf nodes (์ž์‹ ์—†๋Š” Node)

*** Sub Tree ***
	Parent Node
	Child Node
	Siblings (๊ฐ™์€ ๋ ˆ๋ฒจ)

*** Height ***
	Level

2. Tree ๊ตฌํ˜„ํ•˜๊ธฐ

class Tree {
  constructor(value) {
    this.root = new Node(value);
  }
}

class Node {
  children = []; 
  constructor(value) {
    this.value = value;
  }

  push(value){
    this.children.push(new Node(value)); 
    // new Node(value) ํ‘ธ์‹œํ•˜๋Š” ์ด์œ  = ์ž์‹๋„ children ๊ฐ€์งˆ ์ˆ˜ ์žˆ๊ฒŒ๋”
  }
}

const tree = new Tree(50);

์‹คํ–‰๊ฒฐ๊ณผ

const tree = new Tree(50);

tree.root.push(1);
tree.root.push(2);

console.log(
  tree.root.children,
  /* 
  [
  	Node { children: [], value: 1 }, 
    Node { children: [], value: 2 }
  ]
  */
  tree.root.children[0].value, // 1
  tree.root.children[1].value, // 2
)

tree.root.children[0].push(30);
tree.root.children[1].push(31);

console.log(
  tree.root.children[0],
  /*
  	Node { 
    	children: [
        	Node { children: [], value: 30 } 
        ], value: 1 } Node
  */
  
  tree.root.children[1],
  /*
  	Node { 
    	children: [ 
        	Node { children: [], value: 31 } 
       	], value: 2 }
  */
)
profile
ํ˜„์‹ค์ ์ธ ๋ชฝ์ƒ๊ฐ€

0๊ฐœ์˜ ๋Œ“๊ธ€