leetcode-symmetric Tree
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.
原本我的做法,是先求出一棵树的镜像,然后再查看这样的两棵树是不是相等的(isSameTree()请查看本博客leetcode-same tree)
但是卡在了{1,2}这个测试例子上,怎么都通不过。。我的代码如下:(失败)
/** * 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) { // Start typing your C/C++ solution below // DO NOT write int main() function TreeNode *root1 = root; mirror(root1); return isSameTree(root,root1); } void mirror(TreeNode *root){ if(root == NULL){ return; } if(root->left == NULL && root->right == NULL){ return; } //exchange TreeNode *temp = root->left; root->left = root->right; root->right = temp; if(root->left){ mirror(root->left); } if(root->right){ mirror(root->right); } } bool isSameTree(TreeNode *p, TreeNode *q) { if(p==NULL && q==NULL){ return true; } else if(p==NULL || q==NULL){ return false; } if(p->val == q->val){ return isSameTree(p->left,q->left) && isSameTree(p->right,q->right); } else{ return false; } } };
后来查看解答,发现就是node->left->val == node->right->val;node->right->val == node->left->val的一个递归:所以就有如下代码,省去了求镜像的过程:
/** * 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) { // Start typing your C/C++ solution below // DO NOT write int main() function return isSame(root,root); } bool isSame(TreeNode *p, TreeNode *q) { // Start typing your C/C++ solution below // DO NOT write int main() function if(p==NULL && q==NULL){ return true; } else if(p==NULL || q==NULL){ return false; } if(p->val == q->val){ return isSame(p->left,q->right) && isSame(p->right,q->left); } else{ return false; } } };