LC101. Symmetric Tree
#
Problem DescriptionSource: https://leetcode.com/problems/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:
#
Solution#
High level strategyTo check whether two nodes are identical, we can check the following conditions:
- If both nodes are null, then they are the same.
- If one of the nodes is null, then they are not the same.
- If the value of one node is not equal to the value of the other, then they are not the same.
To check whether a tree is symmetrical, we can simply apply the logics above to the opposite nodes on each side of the tree. That is, we compare the right child of the left child with the left child of the right child, so on and so forth. We recurse down both sides of the root node, and return true if and only if both sides return true. The time complexity of this solution is O(n), where 'n' is equal to the number of nodes. The space complexity of this solution is O(logn), or O(h), where 'h' is equal to the height of the tree.
#
Code- Javascript
- Java