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

转载于:https://www.cnblogs.com/Answer1215/p/10388338.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值