Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a recursive binary tree in TypeScript?

Tags:

typescript

I'm trying to create a (generic) binary tree in TypeScript.

I've created an interface which looks like:

interface Node<T> {
    (left?: T): Node<T>,
    (right?: T): Node<T>,
    (data: T): T
}

However, when I do this I get an error message which tells me that "all declarations of 'Node' must have identical type parameters.

Is it possible to create such structures in TypeScript or would I need to do this some other way?

An implementation made without generics appears to work fine.

interface Node {
  left: Node,
  right: Node,
  data: any
}
like image 939
Teymour Aldridge Avatar asked May 12 '20 06:05

Teymour Aldridge


1 Answers

I think you're looking for this (I've used TreeNode rather than Node to avoid DOM conflicts):

interface TreeNode<T> {
    left?: TreeNode<T>;
    right?: TreeNode<T>;
    data: T;
}

Here's an example using it (on the playground):

let tree: TreeNode<string> = {
    data: "b",
    left: {
        data: "a"
    },
    right: {
        data: "c"
    }
};

console.log(tree.data);        // "b"
console.log(tree.left?.data);  // "a"
console.log(tree.right?.data); // "c"
like image 162
T.J. Crowder Avatar answered Oct 05 '22 05:10

T.J. Crowder