Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
For example, this binary tree is symmetric:
1 / \ 2 2 / \ / \ 3 4 4 3
But the following is not:
1 / \ 2 2 \ \ 3 3
Note:
Bonus points if you could solve it both recursively and iteratively.
confused what "{1,#,2,3}"
means? > read more on how binary tree is serialized on OJ.
Analysis:
recursion
situations that left child is same with right child
left.val == right.val or left == right == null
left.left child == right.right child
left.right child == right.left child
java
public boolean isSymmetric(TreeNode root) { if(root==null) return true; return symmetric(root.left, root.right); } public boolean symmetric(TreeNode left, TreeNode right){ if(left == null) return right==null; if(right == null) return left==null; if(left.val!=right.val) return false; if(!symmetric(left.left, right.right)) return false; if(!symmetric(left.right, right.left)) return false; return true; }
bool isSymmetric(TreeNode *root) { if(root == NULL) return true; return symmetric(root->left,root->right); } bool symmetric(TreeNode *left, TreeNode *right){ if(left == NULL) return right==NULL; if(right == NULL) return left==NULL; if(left->val!=right->val) return false; if(!symmetric(left->left,right->right)) return false; if(!symmetric(left->right,right->left)) return false; return true; }