Skip welcome & menu and move to editor
Welcome to JS Bin
Load cached copy from
 
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>
</body>
</html>
 
var insert = function(value, root) {
  if (!root) {
    // Create a new root.
    root = { val: value };
  }
  else {
    var current = root;
    while (current) {
      if (value < current.val) {
        if (!current.left) {
          // Insert left child.
          current.left = { val: value };
          break;
        }
        else {
          current = current.left;
        }
      }
      else if (value > current.val) {
        if (!current.right) {
          // Insert right child.
          current.right = { val: value };
          break;
        }
        else {
          current = current.right;
        }
      }
      else {
        // This value already exists. Ignore it.
        break;
      }
    }
  }
  
  return root;
}
var exists = function(value, root) {
  var result = false;
  
  var current = root;
  while (current) {
    if (value < current.val) {
      current = current.left;
    }
    else if (value > current.val) {
      current = current.right;
    }
    else {
      result = true;
      break;
    }
  }
  
  return result;
}
var traversePre = function(head, callback) {
  // Preorder traversal.
  if (head) {
    if (callback) {
      callback(head.val);
    }
    
    traversePre(head.left, callback);
    traversePre(head.right, callback);
  }
}
var traversePost = function(head, callback) {
  // Postorder traversal.
  if (head) {
    traversePost(head.left, callback);
    traversePost(head.right, callback);
    if (callback) {
      callback(head.val);
    }
  }
}
var traverseIn = function(head, callback) {
  // Inorder traversal.
  var current = head;
  var history = [];
  
  // Move down to the left-most smallest value, saving all nodes on the way.
  while (current) {
    history.push(current);
    current = current.left;
  }
  
  current = history.pop();
  while (current) {
    if (callback) {
      callback(current.val);
    }
    
    // Move to the right, and then go down to the left-most smallest value again.
    current = current.right;
    while (current) {
      history.push(current);
      current = current.left;
    }
    
    current = history.pop();
  }
}
var root = insert(10);
insert(5, root);
insert(6, root);
insert(3, root);
insert(20, root);
Output

You can jump to the latest bin by adding /latest to your URL

Dismiss x
public
Bin info
anonymouspro
0viewers