二进制搜索树解决方案不起作用?

时间:2017-12-05 12:12:57

标签: javascript binary-search-tree

这是一个二叉搜索树,左边的所有节点都较小,右边的所有节点都较大。

我试图创建一个函数isPresent来检查BST中是否存在值。如果是,则返回1.如果否,则返回0.

this.isPresent = function(root, val) {
    if (val == root.data) {
      return 1;
    }

    if (val < root.data) {
      if (root.left) {
        this.isPresent(root.left, val);
      } else {
        return 0;
      }
    } else {
      if (root.right) {
        this.isPresent(root.right, val);
      } else {
        return 0;
      }
    }
  }

整个代码:

function Node(data) {
  this.data = data;
  this.left = null;
  this.right = null;
};

function BinarySearchTree() {
  this.insert = function(root, data) {
    if (root === null) {
      this.root = new Node(data);

      return this.root;
    }

    if (data < root.data) {
      if (root.left) {
        this.insert(root.left, data);
      } else {
        root.left = new Node(data);
      }
    } else {
      if (root.right) {
        this.insert(root.right, data);
      } else {
        root.right = new Node(data);
      }
    }
    return this.root;
  }

  this.isPresent = function(root, val) {
    if (val == root.data) {
      return 1;
    }

    if (val < root.data) {
      if (root.left) {
        this.isPresent(root.left, val);
      } else {
        return 0;
      }
    } else {
      if (root.right) {
        this.isPresent(root.right, val);
      } else {
        return 0;
      }
    }
  }
}

如何格式化输入:

process.stdin.resume();
process.stdin.setEncoding('ascii');

var _input = "";

process.stdin.on('data', function(data) {
  _input += data;
});

process.stdin.on('end', function() {
  var tree = new BinarySearchTree();
  var root = null;

  var values = _input.spit('\n').map(Number);

  var j = 1;

  for (var i = 0; i < values[0]; i++) {
    root = tree.insert(root, values[j]);

    j++;
  }

  var k = j + 1;

  for (var i = 0; i < values[j]; i++) {
    process.stdout.write(tree.isPresent(root, values[k]) + '\n');

    k++;
  }
})

示例输入:

11 <--- this line indicating next 11 lines are values to be inserted to BST
20
10
30
8
12
25
40
6
11
13
23
4 <--- this line indicated the next 4 lines to be tested whether they are present in BST
30
10
12
15

0 个答案:

没有答案