Problem
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
Code
bool isSymmetric_r(TreeNode *l,TreeNode *r) { if(!l && !r) return true; if(!l || !r) return false; if(l->val != r->val) return false; return (isSymmetric_r(l->left,r->right) && isSymmetric_r(l->right,r->left)); } bool isSymmetric(TreeNode *root) { // IMPORTANT: Please reset any member data you declared, as // the same Solution instance will be reused for each test case. return isSymmetric_r(root,root); }
No comments:
Post a Comment