简体   繁体   English

创建二叉树的时间复杂度

[英]Time Complexity of Creating a Binary Tree

I am trying to create a tree from a source that provides: the 2 nodes to be added to the tree, and the node which these 2 news nodes should be added. 我正在尝试从提供以下内容的源创建树:要添加到树的2个节点,以及应添加这2个新闻节点的节点。 To find where this node is in the tree, I used a inorder traversal which takes O(n). 为了找到这个节点在树中的位置,我使用了一个带有O(n)的inorder遍历。 So if there was n number of nodes to be added in the tree, will the creation of the whole tree be O(n^2). 因此,如果在树中添加了n个节点,则整个树的创建将是O(n ^ 2)。 My constraint is that it should only take O(n) to create the tree. 我的约束是它应该只用O(n)来创建树。

Looking up a node in a binary tree is O(log(n)) because the tree has log(n) levels (each level holds twice as much as the level above it). 查找二叉树中的节点是O(log(n))因为树具有log(n)级别(每个级别保持两倍于其上面的级别)。 Therefore to create/insert n elements into a binary tree it's O(nlog(n)) . 因此,要在二叉树中创建/插入n元素,它就是O(nlog(n))

You could keep references to each node of the tree in a HashMap [1], to get O(1) access to each node instead of the O(log(n)) which is typical of trees. 您可以在HashMap [1]中保留对树的每个节点的引用,以获得对每个节点的O(1)访问,而不是树(典型的O(log(n)) That would make it possible to build the tree in O(n) time, because that HashMap lets you jump directly to a node instead of traversing there from the tree's root node. 这样就可以在O(n)时间内构建树,因为HashMap允许您直接跳转到节点而不是从树的根节点遍历。

[1] The key would be whatever the source uses for uniquely identifying the nodes (I'm assuming it to be an integer or string). [1]密钥将是源用于唯一标识节点的任何内容(我假设它是一个整数或字符串)。 The value would be a reference to the node in the tree. 该值将是对树中节点的引用。 Note that the tree implementation must make all its nodes public, so you will probably need to write the tree yourself or find a suitable library (JDK's trees such as TreeMap keep their internal structure private, so they won't cut it). 请注意,树实现必须使其所有节点都公开,因此您可能需要自己编写树或找到合适的库(例如TreeMap的JDK树保持其内部结构为私有,因此它们不会删除它)。

for Binary search tree time complexity will be O(nlogn) when the elements are not sorted and sorted it takes O(n^2). 对于二元搜索树时间复杂度将是O(nlogn),当元素未被排序和排序时,它需要O(n ^ 2)。 It is because to to insert one element in a sorted list in a BST O(n) time is taken so for n elements O(n^2) and for a balanced or almost balanced binary search tree max time for insertion is logn so for n elements it is nlogn 这是因为要在BST O(n)中对一个排序列表中插入一个元素,因此对于n个元素O(n ^ 2),对于平衡或几乎平衡的二叉搜索树,插入的最大时间是logn,因此对于n个元素是nlogn

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM