栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

插入二进制搜索树(BST)时计算较小值的数量

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

插入二进制搜索树(BST)时计算较小值的数量

您可以在每个节点中存储连接到左侧(小于)的叶子数,并在插入新叶子时增加在左侧传递的每个分支的计数。

通过将插入时在右侧传递的所有分支计数相加,可以同时计算小于新插入值的值数。

下面是一个Javascript代码片段来演示该方法:

function CountTree() {     // tree constructor    this.root = null;    this.insert = function(value) {        var branch = null, node = this.root, count = 0, after;        while (node != null) {        // traverse tree to find position branch = node; after = value > node.value;          // compare to get direction if (after) {     node = branch.right;  // pass on the right (greater)     count += branch.count;// add all nodes to the left of branch } else {     node = branch.left;   // pass on the left (smaller or equal)     ++branch.count;       // increment branch's count }        }       // attach new leaf        if (branch == null) this.root = new Leaf(value);        else if (after) branch.right = new Leaf(value);        else branch.left = new Leaf(value);        return count;    }    function Leaf(value) { // leaf constructor        this.value = value;        this.left = null;        this.right = null;        this.count = 1;    }}var t = new CountTree(), v = [5, 3, 8, 2, 4, 7, 9, 1, 4, 7, 8];for (var i in v) {    document.write("Inserting " + v[i] + " (found " + t.insert(v[i]) + " smaller)<BR>");}

这是代码示例中的树,当插入最后一个元素(第二个值8)时。每个节点的左侧顶点(包括其自身)的节点数打印在其右侧顶点的下方。当插入第二个8时,传递值为5、8和7的节点。其中,5和7在右侧传递,它们的计数之和为6
+ 2 = 8,所以在树中有8个比8小的值:1、2、3、4、4、5、7 7.第一个值为8的节点在左侧传递,因此其计数将从3递增到4。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/637418.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号