简体   繁体   中英

how to find value is present in binary tree or not

please anyone tell me how to find value is present or not in binary tree ? i want to find value is present in left or right node of binary tree?

BinarySearchTree.prototype = {

  //more code

  contains: function(value){
    var found       = false,
        current     = this._root

    //make sure there's a node to search
    while(!found && current){

      //if the value is less than the current node's, go left
      if (value < current.value){
        current = current.left;

        //if the value is greater than the current node's, go right
      } else if (value > current.value){
        current = current.right;

        //values are equal, found it!
      } else {
        found = true;
      }
    }

    //only proceed if the node was found
    return found;
  }
}

Instead of looping with while I suggest using a recursive approach.

function searchBST(rootNode, val) {
    if (rootNode.key === null)
        return null;

    var nodeKey = parseInt(rootNode.val);
    if (val < nodeKey) {
        return searchBST(rootNode.left, val);
    } else if (val > nodeKey) {
        return searchBST(rootNode.right, val);
    } else {
        return rootNode.value;
    }
}

This function will return the node with the searched value, if you want to only check the presence or not of a node with a certain value, just edit the return values with false and true

You can just leave the function if the value is found in the tree.

 function Node(value) { this.value = value; // this.left = null; // this.right = null; } function BinarySearchTree() { this._root = null; } BinarySearchTree.prototype = { insert: function (value) { var node = this, side = '_root'; while (node[side]) { node = node[side]; if (value === node.value) { return; } side = value < node.value ? 'left' : 'right'; } node[side] = new Node(value); }, contains: function (value) { var current = this._root while (current) { document.write('value: ' + current.value + '<br>'); if (value === current.value) { return true; // leave the function } current = value < current.value ? current.left : current.right; } return false; }, }; var tree = new BinarySearchTree(), i; for (i = 0; i < 10; i++) { tree.insert(Math.floor(Math.random() * 1000)); } document.write(tree.contains(42) + '<br>'); tree.insert(42); document.write(tree.contains(42) + '<br>'); document.write('<pre>' + JSON.stringify(tree, 0, 4) + '</pre>'); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM