Open zerozoo-a opened 1 year ago
class TreeNode { constructor(v,l,r){ this.v = v; this.l = l; this.r = r; } insert(v){ if(v < this.v) { if(!this.l) { this.l = new TreeNode(v) } else { this.l.insert(v) } } else { if(!this.r) { this.r = new TreeNode(v) } else { this.r.insert(v) } } } *[Symbol.iterator](){ if(this.l) yield* this.l; yield this.v; if(this.r) yield* this.r; } } const root = new TreeNode(5); root.insert(1); root.insert(2); root.insert(3); root.insert(4); [...root] // [1, 2, 3, 4, 5]
class Tree { constructor(v,l,r){ this.v = v; this.l = l; this.r = r; } insert(v){ if(v === this.v) return; if(v < this.v) { if(!this.l) { this.l = new Tree(v); } else { this.l.insert(v); } } else { if(!this.r) { this.r = new Tree(v); } else { this.r.insert(v); } } } *[Symbol.iterator](a) { let _a = a; if(_a === 'lvr') { if(this.l) yield* this.l; yield this.v; if(this.r) yield* this.r; } else if(_a === 'rvl'){ if(this.r) yield* this.r; yield this.v; if(this.l) yield* this.l; } else { yield this.v; if(this.l) yield* this.l; if(this.r) yield* this.r; } } } const root = new Tree(3); root.insert(1); root.insert(2); root.insert(4); root.insert(5); const lvr = root[Symbol.iterator]('lvr'); [...lvr] // [1,2,3,4,5] const rvl = root[Symbol.iterator]('rvl'); [...rvl] // [4,5,3,1,2] const vlr = root[Symbol.iterator](); [...vlr] // [3,1,2,4,5]
class TreeNode { constructor(val, left, right) { Object.assign(this, { val, left, right }); } insert(val) { if (val < this.val) { if (!this.left) { this.left = new TreeNode(val); } else { this.left.insert(val); } } else if (val > this.val) { if (!this.right) { this.right = new TreeNode(val); } else { this.right.insert(val); } } } inorder(node) { if (!node) return; this.inorder(node.left); console.log(node.val); this.inorder(node.right); } preorder(node) { if (!node) return; console.log(node.val); this.preorder(node.left); this.preorder(node.right); } postorder(node) { if (!node) return; this.postorder(node.left); this.postorder(node.right); console.log(node.val); } *gInorder() { if (this.left) yield* this.left.gInorder(); yield this.val; if (this.right) yield* this.right.gInorder(); } *gPreorder() { yield this.val; if (this.left) yield* this.left.gPreorder(); if (this.right) yield* this.right.gPreorder(); } *gPostorder() { if (this.left) yield* this.left.gPostorder(); if (this.right) yield* this.right.gPostorder(); yield this.val; } } const root = new TreeNode(4); root.insert(3); root.insert(5); root.insert(1); root.insert(6); root.insert(7); root.insert(2); const pre = root.gPreorder(); console.log(pre.next()); console.log(pre.next()); console.log(pre.next()); console.log(pre.next()); console.log([...pre]); root.preorder(root);