[英]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.