From 90df0100f63748c9527fdb63dcb16962cfe08b45 Mon Sep 17 00:00:00 2001 From: andy922200-m1 Date: Fri, 5 Apr 2024 16:19:37 +0800 Subject: [PATCH] feat: finish BST print --- app-ch9-13.js | 73 ++++++++++++++++++++++++++++++++++++++++++++------- 1 file changed, 64 insertions(+), 9 deletions(-) diff --git a/app-ch9-13.js b/app-ch9-13.js index 09c7fb2..7dacea2 100644 --- a/app-ch9-13.js +++ b/app-ch9-13.js @@ -9,6 +9,8 @@ class Node { class BinarySearchTree { constructor() { this.root = null; + this.path = ''; + this.queue = []; } treeInsert(z) { @@ -28,15 +30,68 @@ class BinarySearchTree { y.right = z; } } + + preOrder(n){ + if(n !== null){ + this.path += n.key + ' '; + this.preOrder(n.left); + this.preOrder(n.right); + } + } + + inOrder(n){ + if(n !== null){ + this.inOrder(n.left); + this.path += n.key + ' '; + this.inOrder(n.right); + } + } + + postOrder(n){ + if(n !== null){ + this.postOrder(n.left); + this.postOrder(n.right); + this.path += n.key + ' '; + } + } + + bftt(n){ + if(n !== null){ + this.queue.push(n); + for(let i=0; i{ + bst1.treeInsert(new Node(seed)); + bst2.treeInsert(new Node(seed)); + bst3.treeInsert(new Node(seed)); + bst4.treeInsert(new Node(seed)); +}) -console.log(bst); \ No newline at end of file +bst1.preOrder(bst1.root) +bst2.inOrder(bst2.root) +bst3.postOrder(bst3.root) +bst4.bftt(bst4.root) +console.log('PreOrder:', bst1.path) +console.log('InOrder:', bst2.path) +console.log('PostOrder:', bst3.path) +console.log('BFTT:', bst4.queue.map(node => node.key).join(' ')) \ No newline at end of file