递归类

typescript
阅读 48 收藏 0 点赞 0 评论 0

RecursiveClass.ts
class MyNode {
  parentNode: MyNode;
  nextNodes: Array<MyNode>;
  data: string;

  constructor(text: string) {
      this.data = text;
      this.nextNodes = [];
  }

    append(newElem: MyNode) {
        newElem.parentNode = this;
        this.nextNodes.push(newElem);
    }

    print(node: MyNode, depth: number = 0) { 
        for (let i in node.nextNodes) { 
            node.print(node.nextNodes[i], depth++);
        }

        if (node.nextNodes.length == 0) { 
            console.warn(this.data);
        } 
    }
}

const tmp = new MyNode("hello");
const other1 = new MyNode("test name");
other1.append(new MyNode("good"));
other1.append(new MyNode("boy"));

const other2 = new MyNode("test name 2");
other2.append(new MyNode("bad"));
other2.append(new MyNode("boy"));

tmp.append(other1);
tmp.append(other2);

tmp.print(tmp);
评论列表


问题


面经


文章

微信
公众号

扫码关注公众号