- Notifications
You must be signed in to change notification settings - Fork66
Open
Description
letnode=(data)=>({left:null,right:null,data:data})letbst={root:null,insert:(root=bst.root,data)=>{if(root===null){bst.root=node(data);}else{if(data<root.data){root.left=root.left===null ?node(data) :bst.insert(root.left,data);}else{root.right=root.right===null ?node(data) :bst.insert(root.right,data);}}returnroot;},postorder:(root)=>{if(root!==null){bst.postorder(root.left);bst.postorder(root.right);console.log(root.data);}},inorder:(root)=>{if(root!==null){bst.inorder(root.left);console.log(root.data);bst.inorder(root.right);}},remove:(root,data)=>{if(root===null)returnnull;elseif(data>root.data){root.right=bst.remove(root.right,data);returnroot;}elseif(data<root.data){root.left=bst.remove(root.left,data);returnroot;}else{if(root.left==null&&root.right===null){root=null;returnroot;}if(root.left===null){root=root.right;returnroot;}elseif(root.right===null){root=root.left;returnroot;}// Deleting node with two children// minumum node of the rigt subtree// is stored in auxletaux=bst.findMinNode(root.right);root.data=aux.data;root.right=bst.remove(root.right,aux.data);returnroot;}},findMinNode:(root)=>{if(root.left===null)returnroot;root=bst.findMinNode(root.left);returnroot;}}bst.insert(bst.root,15);bst.insert(bst.root,25);bst.insert(bst.root,10);bst.insert(bst.root,7);bst.insert(bst.root,22);bst.insert(bst.root,17);bst.insert(bst.root,13);bst.insert(bst.root,5);bst.insert(bst.root,9);bst.insert(bst.root,27);console.log(JSON.stringify(bst.root));bst.remove(bst.root,5);bst.remove(bst.root,7);// bst.inorder(bst.root);bst.remove(bst.root,15);bst.inorder(bst.root);