create a tree type in typescript

Here is an example of how to create a simple tree structure in TypeScript using classes:

index.ts
class TreeNode<T> {
  public value: T
  public children: TreeNode<T>[]

  constructor(value: T) {
    this.value = value
    this.children = []
  }

  addChild(node: TreeNode<T>): void {
    this.children.push(node)
  }

  removeChild(node: TreeNode<T>): void {
    const index = this.children.indexOf(node)
    if (index !== -1) {
      this.children.splice(index, 1)
    }
  }
}

const root = new TreeNode("Parent")
const child1 = new TreeNode("Child 1")
const child2 = new TreeNode("Child 2")

root.addChild(child1)
root.addChild(child2)

console.log(root)  // Output: TreeNode { value: 'Parent', children: [ TreeNode { value: 'Child 1', children: [] }, TreeNode { value: 'Child 2', children: [] } ] }
705 chars
30 lines

You can add more functionalities to TreeNode class as per the requirement. You can also use recursion to iterate over the tree's nodes and perform various operations like printing, finding a node, etc.

gistlibby LogSnag