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
/ \
2 2
/ \ / \
3 4 4 3
But the following [1,2,2,null,3,null,3]
is not:
1
/ \
2 2
\ \
3 3
Note:
Bonus points if you could solve it both recursively and iteratively.
Solution1: recursion
- Bottom-up,
看left.left && right.right
和left.right && right.left
是否是symmetric, 如果是,再看left.val == right.val?
- Base Case:
left 和right任一一个不为null,则不是对称,返回false
left和right都为null,则对称,返回true
class Solution {
//// ********* Recursion solution ****************/
public boolean isSymmetric(TreeNode root) {
if (root == null) {
return true;
}
return isSymmetricHelper (root.left, root.right);
}
private boolean isSymmetricHelper (TreeNode left, TreeNode right) {
if (left == null && right == null) {
return true;
}
if (left == null || right == null) {
return false;
}
return left.val == right.val && isSymmetricHelper (left.left, right.right) && isSymmetricHelper (left.right, right.left);
}
Solution2: Iteration
- 与Same Tree那题很像,比较就是
root.left, root.right
是否的对称的same tree
//// ********* Iteration solution ****************/
public boolean isSymmetric(TreeNode root) {
if (root == null) {
return true;
}
Queue tracker1 = new LinkedList<> ();
Queue tracker2 = new LinkedList<> ();
tracker1.offer (root.left);
tracker2.offer (root.right);
while (!tracker1.isEmpty () && !tracker2.isEmpty ()) {
TreeNode left = tracker1.poll ();
TreeNode right = tracker2.poll ();
// 有可能某一层,不是满的
if (left == null && right == null) {
continue;
}
if (left == null || right == null) {
return false;
}
if (left.val != right.val) {
return false;
}
tracker1.offer (left.left);
tracker1.offer (left.right);
tracker2.offer (right.right);
tracker2.offer (right.left);
}
if (!tracker1.isEmpty () || !tracker2.isEmpty ()) {
return false;
}
return true;
}
//// ********* Iteration solution END ****************/