description:
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.
The serialization of a binary tree follows a level order traversal, where '#' signifies a path terminator where no node exists below.
Here's an example:
1 / \ 2 3 / 4 \ 5The above binary tree is serialized as
"{1,2,3,#,#,4,#,#,5}"
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: bool isSymmetric(TreeNode *root) { // Note: The Solution object is instantiated only once and is reused by each test case. if(root == NULL) return true; TreeNode *syroot = new TreeNode(root->val); build(syroot->left,root->right); build(syroot->right,root->left); if(isSameTree(syroot,root)) return true; else return false; } void build(TreeNode *&syroot,TreeNode *root) { if(root == NULL) { syroot = NULL; return; } syroot = new TreeNode(root->val); build(syroot->left,root->right); build(syroot->right,root->left); } bool isSameTree(TreeNode *p, TreeNode *q) { // Start typing your C/C++ solution below // DO NOT write int main() function if(p == NULL && q == NULL) return true; if((p == NULL && q !=NULL) || (p !=NULL && q == NULL)) return false; if(p->val != q->val) return false; if(!issame(p->left,q->left)) return false; if(!issame(p->right,q->right)) return false; return true; } bool issame(TreeNode *p, TreeNode *q) { if((p == NULL && q !=NULL) || (p !=NULL && q == NULL)) return false; if(p == NULL && q == NULL) return true; if(p->val != q->val) return false; if(!issame(p->left,q->left)) return false; if(!issame(p->right,q->right)) return false; return true; } };
下面的代码更简洁,不用构造一颗对称树:但是时间复杂度并没有优化多少
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: bool isSymmetric(TreeNode *root) { // Note: The Solution object is instantiated only once and is reused by each test case. if(root == NULL) return true; return isSame(root,root); } bool isSame(TreeNode *syroot,TreeNode *root) { if(syroot == NULL && root == NULL) return true; else if(syroot == NULL || root == NULL) return false; if(syroot->val != root->val) return false; return isSame(syroot->left,root->right) && isSame(syroot->right,root->left); } };