加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

[Algorithm] Construct a Binary Tree and Binary Search

发布时间:2020-12-14 04:24:15 所属栏目:大数据 来源:网络整理
导读: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)
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.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读