Advertisement
anyafachri

BST Insert

Nov 22nd, 2022
70
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
JavaScript 1.10 KB | Source Code | 0 0
  1. class Node {
  2.     constructor(val){
  3.         this.right = null
  4.         this.left = null
  5.         this.value = val
  6.     }
  7. }
  8.  
  9. function insert(node, val){
  10.     if(!node) return new Node(val)      
  11.        
  12.     if(node.value < val){
  13.         node.right = insert(node.right, val);
  14.     } else {
  15.         node.left = insert(node.left, val);
  16.     }
  17.  
  18.     return node  
  19. }
  20.  
  21. function traverse(node){
  22.     if(node == null) return
  23.    
  24.     process.stdout.write(node.value.toString()+" ")
  25.    
  26.     traverse(node.left)
  27.     traverse(node.right)
  28. }
  29.  
  30.  
  31. function processData(input) {
  32.     // process input
  33.     input = input.split(" ")
  34.     input[0] = input[0].split("\n")[1]
  35.    
  36.     input = input.map(v => Number(v))
  37.    
  38.     let root = null
  39.                    
  40.     // console.log(input)                    
  41.     input.forEach(v => {
  42.         root = insert(root, v)
  43.     })
  44.     traverse(root)
  45. }
  46.  
  47. process.stdin.resume();
  48. process.stdin.setEncoding("ascii");
  49. _input = "";
  50. process.stdin.on("data", function (input) {
  51.     _input += input;
  52. });
  53.  
  54. process.stdin.on("end", function () {
  55.    processData(_input);
  56. });
  57.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement