From ef3014e53832b6c807eb033d8274c59da3b4cb4a Mon Sep 17 00:00:00 2001 From: Jon Sakas Date: Thu, 2 Jun 2022 14:00:37 -0600 Subject: [PATCH] feat: support passing tree as value to insert --- src/MAryTree.test.ts | 21 ++++++++++++++++++++- src/MAryTree.ts | 17 ++++++++++++++--- 2 files changed, 34 insertions(+), 4 deletions(-) diff --git a/src/MAryTree.test.ts b/src/MAryTree.test.ts index 4203cdc..4d93ded 100644 --- a/src/MAryTree.test.ts +++ b/src/MAryTree.test.ts @@ -1,4 +1,4 @@ -import { MAryTree, MAryTreeNode } from "./MAryTree"; +import { MAryTree } from "./MAryTree"; describe('MAryTree', () => { it('creates tree with single node', () => { @@ -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]); + }); }); \ No newline at end of file diff --git a/src/MAryTree.ts b/src/MAryTree.ts index 5b1ba4c..6ef1e69 100644 --- a/src/MAryTree.ts +++ b/src/MAryTree.ts @@ -345,7 +345,7 @@ export class MAryTree { insert( parentNodeKey: K, key: K, - value?: T, + value?: T | MAryTree, ): MAryTreeNode | null { const parent = this.find(parentNodeKey); @@ -356,10 +356,21 @@ export class MAryTree { throw new Error('Cannot insert child node: parent already has max children'); } - const node = new MAryTreeNode(key, value, parent); + let node : MAryTreeNode | null = null; - parent.children.push(node); + if (value && 'root' in value) { + node = new MAryTreeNode(key, value.root.value, parent); + for (const child of value.root.children) { + child.parent = node + node.children.push(child); + } + } else { + node = new MAryTreeNode(key, value as T, parent); + } + + parent.children.push(node); + return node; }