简体   繁体   English

以 O(log n) 获取二叉树的大小

[英]Get size of a binary tree in O(log n)

Full disclosure: This is Homework .完全披露:这是作业

I'm asked to return the rank in a Binary Tree, and after some coding I got it to work.我被要求返回二叉树中的排名,经过一些编码后我让它工作。 But since my code doesn't get accepted, I noticed that the code should run in O(log n)但是由于我的代码没有被接受,我注意到代码应该在O(log n)

And the culprit that slowes this down is my size method:减慢速度的罪魁祸首是我的大小方法:

public int size(Node node){
    if (node != null) return (size(node.left) + 1 + size(node.right));
    return 0;
}

Which I call to get the rank of all elements smaller than the one I need to look for.我调用它以获得比我需要查找的元素小的元素的等级。

Now, I googled and all, but apparentely it is not possible to get the size of a BT in log n time?现在,我用谷歌搜索了所有内容,但显然不可能在 log n 时间内获得 BT 的大小?

How would I need to do this then?那我需要怎么做呢?

With a simple binary tree that only stores children, it isn't possible to get the size in O(log(n)) time since there are n nodes, and you must count every one of them.使用仅存储子节点的简单二叉树,由于有 n 个节点,因此无法在 O(log(n)) 时间内获得大小,并且您必须计算每个节点。 However, why restrict yourself to only having children?但是,为什么要限制自己只生孩子呢? Like many data structures, you can store the size with the node:像许多数据结构一样,您可以使用节点存储大小:

class Node {
    public Node left;
    public Node right;
    public int value;
    private int size; // initialize this to 1
}

Then, when inserting into the node, increment the size of every node you encounter:然后,在插入节点时,增加遇到的每个节点的大小:

public void insert(int value) {
    // increment the size
    this.size++;
    if (value < this.value) {
        // obviously check for null as well and insert as appropriate
        this.left.insert(value);
    } else {
        this.right.insert(value);
    }
}

Now, you can get the size in O(1) time, since every node has it.现在,您可以在 O(1) 时间内获得大小,因为每个节点都有它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 为什么这个 function 检查二叉树平衡的时间复杂度是 O(n log n)? - Why is the time complexity of this function to check the balance of a Binary Tree O(n log n)? 你如何以 O(log n) 倍的复杂度计算平衡二叉搜索树的高度? - How do you calculate the height of balanced Binary Search Tree in O(log n) times complexity? 为什么这段代码在多次重新计算深度时检查二叉树是否平衡需要时间 O(n log n) ? - Why does this code to check if a binary tree is balanced take time O(n log n) when it recomputes depths multiple times? 二叉树O(n)的InOrder树遍历的时间复杂度? - Time Complexity of InOrder Tree Traversal of Binary Tree O(n)? 二叉树在O(1)中得到最小元素 - Binary tree to get minimum element in O(1) 以O(n)和O(log n)的二进制表示形式计数1,其中n是位数 - Count 1's in binary representation in O(n) and O(log n) where n is number of bits 为什么要添加不平衡二叉搜索树O(n)? - Why is add in unbalanced Binary Search Tree O(n)? 二进制搜索的修改后的实现是否仍为O(log n)? - Is this modified implementation of binary search still O(log n)? 试图证明二进制搜索的复杂性是O(log(n)) - Trying to prove the complexity of binary search is O(log(n)) AVL树给我O(c ^ n)而不是O(log n) - AVL Tree gives me O(c^n) instead of O(log n)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM