Symmetric Tree
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:
But the following[1,2,2,null,3,null,3]
is not:
Note: Bonus points if you could solve it both recursively and iteratively.
Analysis
From https://leetcode.com/articles/symmetric-tree/
Recursive
Check left subtree and right subtree to see if they are mirrors of each other, also the value of root node should be the same.
Complexity Analysis
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 : The number of recursive calls is bound by the height of the tree. In the worst case, the tree is linear and the height is inO(n). Therefore, space complexity due to recursive calls on the stack is O(n) in the worst case.
Iterative
Use queue, when adding to the queue, put right and left children of two nodes in opposite order:
Complexity Analysis
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 : There is additional space required for the search queue. In the worst case, we have to insert O(n) nodes in the queue. Therefore, space complexity is O(n).
Solution
Recursive
Iterative
Last updated