Skip to content

Commit

Permalink
feat: support passing tree as value to insert
Browse files Browse the repository at this point in the history
  • Loading branch information
jsakas committed Jun 6, 2022
1 parent f6742e4 commit ef3014e
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 4 deletions.
21 changes: 20 additions & 1 deletion src/MAryTree.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { MAryTree, MAryTreeNode } from "./MAryTree";
import { MAryTree } from "./MAryTree";

describe('MAryTree', () => {
it('creates tree with single node', () => {
Expand Down Expand Up @@ -268,4 +268,23 @@ describe('MAryTree', () => {
expect(b).toEqual([ 'G', 'H' ]);

});

it('can combine trees', () => {
const bt1 = new MAryTree(1);

const bt2 = new MAryTree(2);

bt2.insert(2, 4);
bt2.insert(2, 5);
bt2.insert(5, 7);

bt1.insert(1, 2, bt2);

bt1.insert(1, 3);
bt1.insert(3, 6);

const a = Array.from(bt1.breadthFirstTraversal()).map(n => n.key);

expect(a).toEqual([ 1, 2, 3, 4, 5, 6, 7]);
});
});
17 changes: 14 additions & 3 deletions src/MAryTree.ts
Original file line number Diff line number Diff line change
Expand Up @@ -345,7 +345,7 @@ export class MAryTree<K = MAryTreeKey, T = MAryTreeValue> {
insert(
parentNodeKey: K,
key: K,
value?: T,
value?: T | MAryTree<K, T>,
): MAryTreeNode<K, T> | null {
const parent = this.find(parentNodeKey);

Expand All @@ -356,10 +356,21 @@ export class MAryTree<K = MAryTreeKey, T = MAryTreeValue> {
throw new Error('Cannot insert child node: parent already has max children');
}

const node = new MAryTreeNode<K, T>(key, value, parent);
let node : MAryTreeNode<K, T> | null = null;

parent.children.push(node);
if (value && 'root' in value) {
node = new MAryTreeNode<K, T>(key, value.root.value, parent);

for (const child of value.root.children) {
child.parent = node
node.children.push(child);
}
} else {
node = new MAryTreeNode<K, T>(key, value as T, parent);
}

parent.children.push(node);

return node;
}

Expand Down

0 comments on commit ef3014e

Please sign in to comment.