微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

[Algorithm] Construct a Binary Tree and Binary Search

function createNode(value) {
  return {
    value,left: null,right: null
  };
}

function BinaryTree(val) {
  return {
    root: null,nodes: [],add(val) {
      const node = createNode(val);
      if (!this.root) {
        this.root = node;
      } else {
        this.downShift(node);
      }
      this.nodes.push(node);
    },downShift(node) {
      let value = node.value;
      let current = this.root;
      while (current) {
        if (value > current.value) {
          if (!current.right) {
            current.right = node;
            break;
          } else {
            current = current.right;
          }
        } else {
          if (!current.left) {
            current.left = node;
            break;
          } else {
            current = current.left;
          }
        }
      }
    },size() {
      return this.nodes.length;
    },search(target) {
      let found = false;
      let current = this.root;
      while (current) {
        if (target > current.value) {
          if (!current.right) {
            return "Not Found";
          }
          current = current.right;
        } else if (target < current.value) {
          if (!current.left) {
            return "Not Found";
          }
          current = current.left;
        } else {
          found = true;
          break;
        }
      }
      return found;
    }
  };
}

const t = new BinaryTree();
t.add(4);
t.add(7);
t.add(3);
t.add(1);
t.add(9);
t.add(2);
t.add(5);
console.log(t.search(8));

 

About how to traverse binary tree,can refer this post.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐