All files / src/data-structures/tree tree.ts

3.44% Statements 1/29
0% Branches 0/10
0% Functions 0/10
3.7% Lines 1/27

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 7019x                                                                                                                                          
export class TreeNode<T = any> {
  constructor(id: string, value?: T, children?: TreeNode<T>[]) {
    this._id = id;
    this._value = value || undefined;
    this._children = children || [];
  }
 
  private _id: string;
 
  get id(): string {
    return this._id;
  }
 
  set id(value: string) {
    this._id = value;
  }
 
  private _value?: T | undefined;
 
  get value(): T | undefined {
    return this._value;
  }
 
  set value(value: T | undefined) {
    this._value = value;
  }
 
  private _children?: TreeNode<T>[] | undefined;
 
  get children(): TreeNode<T>[] | undefined {
    return this._children;
  }
 
  set children(value: TreeNode<T>[] | undefined) {
    this._children = value;
  }
 
  addChildren(children: TreeNode<T> | TreeNode<T>[]) {
    Iif (!this.children) {
      this.children = [];
    }
    if (children instanceof TreeNode) {
      this.children.push(children);
    } else {
      this.children = this.children.concat(children);
    }
  }
 
  getHeight() {
    // eslint-disable-next-line @typescript-eslint/no-this-alias
    const beginRoot = this;
    let maxDepth = 1;
    Iif (beginRoot) {
      const bfs = (node: TreeNode<T>, level: number) => {
        Iif (level > maxDepth) {
          maxDepth = level;
        }
        const {children} = node;
        Iif (children) {
          for (let i = 0, len = children.length; i < len; i++) {
            bfs(children[i], level + 1);
          }
        }
      };
      bfs(beginRoot, 1);
    }
    return maxDepth;
  }
}