Well normally if using depth-first traversal, we get O(n)
time. However, if we find the minimum element first then call the successor()
method n
times, what time complexity will it be?
I think it may be O(n log n)
because successor is O(log n)
but that doesn't seem right. Can anyone offer any in-depth analysis here (probably involving some limit analysis)?
Time Complexity Analysis: Hence, if a tree has n nodes, then each node is visited only once in inorder traversal and hence the complexity of the inorder traversal of the binary tree is O ( n ) O(n) O(n) .
6. What is the time complexity of level order traversal? Explanation: Since you have to go through all the nodes, the complexity becomes O(n).
for 1 insert operation, avg case is O(lgn) and worst case is O(n) . For n insert operations, avg case is O(nlgn) and worst case is O(n^2) . But usually people refer to complexity of 1 insert operation.
The easiest way to implement the inOrder traversal algorithm in Java or any programming language is by using recursion. Since the binary tree is a recursive data structure, recursion is the natural choice for solving a tree-based problem.
If parent pointers are present at each node, calling the successor method n times takes O(n) time. To see this observe that each edge in the tree gets visited at most twice (once from parent to child and once from child to the parent) by all the successor calls combined. Thus the total number of edges visited by all the successor calls is at most 2n. So the running time is O(n).
Now if parent pointers are not present, in every call we have to start from the root and search for the successor element by travelling through O(log n) nodes (if the tree is balanced). So the complexity becomes O(n log n).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With