title: How to use recursion function to traverse tree in Javascript
body: <p>I was building a tree traverse function and it has to use recursion.</p>
  
  <p>What I want the output to be is</p>
  
  <blockquote>
    <p><code>'{"value":9,"left":{"value":4,"left":{"value":1},"right":{"value":6}},"right":{"value":20,"left":{"value":15},"right":{"value":170}}}'</code></p>
  </blockquote>
  
  <p>Could someone figure out how to use recursion in the <code>traverse</code> function to get the output?</p>
  
  <p>Here is my JS:</p>
  
  <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>   
      class Node {
         constructor(value){
         this.left = null;
         this.right = null;
         this.value = value;
        }
       }
  
      class BinarySearchTree {
           constructor(){
           this.root = null;
       }
      insert(value){
          const newNode = new Node(value);
      if (this.root === null) {
          this.root = newNode;
      } else {
          let currentNode = this.root;
          while(true){
          if(value &lt; currentNode.value){
            //Left
            if(!currentNode.left){
              currentNode.left = newNode;
              return this;
            }
            currentNode = currentNode.left;
          } else {
            //Right
            if(!currentNode.right){
              currentNode.right = newNode;
              return this;
            } 
            currentNode = currentNode.right;
            }
           }
          }
         }  
        }
  
       const tree = new BinarySearchTree();
       tree.insert(9)
       tree.insert(4)
       tree.insert(6)
       tree.insert(20)
       tree.insert(170)
       tree.insert(15)
       tree.insert(1)
       JSON.stringify(traverse(tree.root))
  
      //     9
     //  4     20
     //1  6  15  170
  
    function traverse(node) {
        const tree = { value: node.value };
        tree.left=node.left
         if(node.left===null) {
              return  null
        }else{
             traverse(node.left);
        }     
        tree.right=node.right
            if(node.right===null) {
                   return null
            }else{
                   traverse(node.right);
              }
         }</code></pre>
  </div>
  </div>
  </p>