Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
Example :
1
/ \
2 2
/ \ / \
3 4 4 3
The above binary tree is symmetric. But the following is not:
1
/ \
2 2
\ \
3 3
Return 0 / 1 ( 0 for false, 1 for true ) for this problem
Method:
DFS
Solution:
Time: O(n) Space: O(1)
/** * Definition for binary tree * class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { * val = x; * left=null; * right=null; * } * } */ public class Solution { public int isSymmetric(TreeNode A) { if (A == null) return 1; return helper(A.left, A.right); }
private int helper(TreeNode left, TreeNode right) { if (left == null && right == null) return 1; if (left == null || right == null) return 0; if (left.val != right.val) return 0; return Math.min(helper(left.left, right.right), helper(left.right, right.left)); } }