Skip to content

Commit

Permalink
delete complete
Browse files Browse the repository at this point in the history
  • Loading branch information
yunnniverse committed Nov 29, 2023
1 parent 660d69d commit 5aa6ac8
Showing 1 changed file with 32 additions and 15 deletions.
47 changes: 32 additions & 15 deletions Frontend/algoverse/src/library/tree/BinaryTree.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import {options} from "../../config";

class Node {
static counter = 0;


constructor(value, parent = null) {
this.id = Node.counter;
Expand Down Expand Up @@ -50,12 +51,21 @@ class Node {

_compareValues(item, itemValue, thisValue) {
if (itemValue < thisValue) {
this.addLeftChild(item)
if (this.left) {
this.left.insert(item);
} else {
this.addLeftChild(item);
}
} else if (itemValue > thisValue) {
this.addRightChild(item)
if (this.right) {
this.right.insert(item);
} else {
this.addRightChild(item);
}
} else {
// special case for equality
this._handleEqual(item, itemValue, thisValue);
// Special case for equality (already exists)
console.log("Value already exists in the tree");
// You can choose to throw an error, log a message, or handle it as needed
}
}

Expand All @@ -71,44 +81,51 @@ class Node {
let itemValue = this._convert(item);
if (this.value) {
let thisValue = this._convert(this.value);
this._compareValues(item, itemValue, thisValue)
this._compareValues(item, itemValue, thisValue);
} else {
this.value = item;
}
}

delete(item) {
delete(item) { // 완성 root가 자식이 하나만 있따면? 아니면 없다면?
let itemValue = this._convert(item);

if (!this.value) {
return this; // 트리가 비어있거나 현재 노드가 null일 경우, 현재 노드를 그대로 반환
}

let thisValue = this._convert(this.value);

if (itemValue < thisValue && this.left) {
this.left = this.left.delete(item);
if(this.left!=null){ this.left.parent = this; }
} else if (itemValue > thisValue && this.right) {
this.right = this.right.delete(item);
if(this.right!=null){ this.right.parent = this; }
} else if (itemValue === thisValue) {
// 입력값과 현재 노드의 값이 일치하는 경우에만 삭제 수행

if (!this.left) {
if (!this.left && this.right) {
// Case 1: 오른쪽 자식이나 자식이 없는 경우
return this.right;
} else if (!this.right) {
} else if (!this.right && this.left) {
// Case 2: 왼쪽 자식만 있는 경우
return this.left;
} else if (!this.right && !this.left) {
return null;
}

// Case 3: 양쪽 자식이 모두 있는 경우
let minValueNode = this._findMinNode(this.right);
this.value = minValueNode.value;
this.right = this.right.delete(minValueNode.value);
if(this.right!=null){ this.right.parent = this; }
}

return this;
}



_findMinNode(node) {
// Helper function to find the node with the minimum value in a subtree
Expand Down Expand Up @@ -147,8 +164,8 @@ class Node {

return {
nodes,
edges
}
edges
}
}


Expand Down

0 comments on commit 5aa6ac8

Please sign in to comment.