Skip to content

Commit 3345271

Browse files
committed
add time and space
1 parent 4a8152f commit 3345271

File tree

1 file changed

+14
-2
lines changed

1 file changed

+14
-2
lines changed

Trees/Binary Trees/is_symmetric.c++

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
if the left and right subtrees are mirror images of each other.
44
55
Explanation:
6-
6+
77
1. The code defines a class `BinaryTree` representing a binary tree node. It has an `int` value and pointers
88
to its left and right children.
99
2. The `SymmetricalTree` function is the main entry point. It calls the helper function `treesAreMirrored`
@@ -19,7 +19,19 @@
1919
8. The result is printed to the console.
2020
9. Memory cleanup is performed by deleting the dynamically allocated nodes.
2121
22-
Note: This code snippet assumes the use of a C++ compiler and standard library.
22+
The time and space complexity of the given code snippet can be analyzed as follows:
23+
24+
1. Time Complexity:
25+
- The `SymmetricalTree` function calls the `treesAreMirrored` function, which performs a recursive traversal of the binary tree.
26+
- In the worst case, the recursion visits each node once, so the time complexity is O(N), where N is the number of nodes in the tree.
27+
28+
2. Space Complexity:
29+
- The space complexity is determined by the maximum depth of the recursion stack.
30+
- In the worst case, the binary tree is linear, resulting in a recursion depth of N, where N is the number of nodes in the tree.
31+
- Therefore, the space complexity is O(N) due to the recursion stack usage.
32+
33+
It's important to note that the space complexity can be optimized by using an iterative approach instead of recursion. By using an iterative algorithm that leverages a stack or queue to perform a level-order traversal, we can achieve a space complexity of O(W), where W is the maximum width (number of nodes at the same level) of the binary tree.
34+
2335
*/
2436
#include <iostream>
2537

0 commit comments

Comments
 (0)