[Data Structure] JavaScript로 이진탐색트리(BST) 자료형 만들기

[Data Structure] JavaScript로 이진탐색트리(BST) 자료형 만들기

API

new BinarySearchTree (value);

bst. insert (value);

bst. contains (value);

bst. preorder (callback);

bst. inorder (callback);

bst. postorder (callback);

class BinarySearchTree { constructor(value) { this.value = value; this.left = null; this.right = null; } insert(value) { if (value < this.value) { if (this.left === null) { this.left = new BinarySearchTree(value); } else { this.left.insert(value); } } else if (value > this.value) { if (this.right === null) { this.right = new BinarySearchTree(value); } else { this.right.insert(value); } } } contains(value) { if (this.value === value) { return true; } if (value < this.value) { if (this.left !== null) { if (this.left.value === value) { return true; } else { return this.left.contains(value); } } } if (value > this.value) { if (this.right !== null) { if (this.right.value === value) { return true; } else { return this.right.contains(value); } } } return false; } preorder(callback) { callback(this.value); if (this.left) { this.left.preorder(callback); }; if (this.right) { this.right.preorder(callback); }; } inorder(callback) { if (this.left) { this.left.inorder(callback); }; callback(this.value); if (this.right) { this.right.inorder(callback); }; } postorder(callback) { if (this.left) { this.left.postorder(callback); }; if (this.right) { this.right.postorder(callback); }; callback(this.value); } }

from http://dong-jinmyong.tistory.com/11 by ccl(A) rewrite - 2021-11-14 21:27:43