创建二叉树
// 初始化二叉树对象 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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论