Symmetric Tree
LeetCode - 0101 Symmetric Tree
https://leetcode.com/problems/symmetric-tree/
Problem Description
Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center). For example, this binary tree [1, 2, 2, 3, 4, 4, 3] is symmetric:
1 | 1 |
But the following [1, 2, 2, null, 3, null, 3] is not:
1 | 1 |
Solutions
Recursion
1 | /** |
Time complexity: O(n)
Because we traverse the entire input tree once, the total run time is O(n), where n is the total number of nodes in the tree.Space complexity: O(n)
The number of recursive calls is bound by the height of the tree. In the worst case, the tree is linear(unbalanced) and the height is in O(n). Therefore, space complexity due to recursive calls on the stack is O(n) in the worst case.
Iteration
1 | /** |
Time complexity: O(n)
Because we traverse the entire input tree once, the total run time is O(n), where n is the total number of nodes in the tree.Space complexity: O(n)
There is additional space required for the search stack. In the worst case, we have to insert O(n) nodes in the stack. Therefore, space complexity is O(n).