原题:
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和上一道题一样,要中序遍历dfs,不过右子树要反向dfs,结果如下:
Success
Runtime: 0 ms, faster than 100.00% of C++ online submissions for Symmetric Tree.
Memory Usage: 14.7 MB, less than 85.91% of C++ online submissions for Symmetric Tree.
代码:
class Solution { public: bool isSymmetric(TreeNode* root) { if(root==NULL){return true;} return Compare(root->left,root->right); } bool Compare(TreeNode* l,TreeNode* r){ if(l==NULL&&r==NULL){return true;} if(l==NULL||r==NULL){return false;} if(Compare(l->left,r->right)==true){ if(l->val==r->val){ if(Compare(l->right,r->left)==true){ return true; } } } return false; } };
