[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.

相关文章

自1998年我国取消了福利分房的政策后,房地产市场迅速开展蓬...
文章目录获取数据查看数据结构获取数据下载数据可以直接通过...
网上商城系统MySql数据库设计
26个来源的气象数据获取代码
在进入21世纪以来,中国电信业告别了20世纪最后阶段的高速发...