1.9 Symmetric Tree
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
/ \ 2 2 / \ / \ 3 4 4 3 But the following [1,2,2,null,3,null,3] is not: 1 / \ 2 2 \ \ 3 3
Method
- recursive check equality and the most left one with the most right one
iteratively stack
Time and Space Complexity
o(n) o(n)
Code
public class Solution { // recursive
public boolean isSymmetric(TreeNode root) { if (root == null){ return true; } return check(root.left, root.right); } public boolean check(TreeNode leftR, TreeNode rightR){ if (leftR == null || rightR == null){ return leftR == rightR; } if (leftR.val != rightR.val){ return false; } return check(leftR.left, rightR.right) && check(leftR.right, rightR.left);
}
}
// iteratively
public boolean isSymmetric(TreeNode root) {
if (root == null){
return true;
}
Stack
}