创建二叉树

发布于 2022-03-07 13:11:14 字数 1096 浏览 843 评论 0

// 初始化二叉树对象
function Node(data, left, right, parent) {
  this.data = data;
  this.left = left;
  this.right = right;
  this.parent = parent;
  this.show = function () {
    return this.data;
  }
}
// 定义插入对象
function BST() {
  this.root = null;
  this.insert = insert;
}

function insert(data) {
  //实例化Node对象
  let n = new Node(data, null, null);
  //如果不存在节点,则此节点为根节点
  if (this.root == null) {
    this.root = n;
  } else {
    //存在根节点,定义current
    let current = this.root;
    let parent;
    while (true) {
      parent = current;
      //当插入值小于根节点的值时,将值作为左节点
      if (data < current.data) {
        current = current.left;
        if (current == null) {
          parent.left = n;
          break;
        }
      } else {
        //当插入的值大于根节点值,将值作为右节点
        current = current.right;
        if (current == null) {
          parent.right = n;
          break;
        }
      }
    }
  }
}

const bst = new BST();
bst.insert(13);
bst.insert(21);
bst.insert(15);
bst.insert(29);
bst.insert(3);
bst.insert(55);
bst.show();

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文