地址:http://oj.leetcode.com/problems/symmetric-tree/
跟上一题类似:http://blog.youkuaiyun.com/flyupliu/article/details/21514553
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.
思路:跟上一题类似,只是把p->left与q->right 比较,p->right与q->left比较。注意与上一题代码的异同。
非递归方法还没写,待续。
参考代码:
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
bool is_sub_symm(TreeNode* p, TreeNode* q)
{
if(p && q)
{
if(p->val == q->val && is_sub_symm(p->left, q->right))
{
return is_sub_symm(p->right, q->left);
}
}
else if(!p && !q)
{
return true;
}
return false;
}
class Solution {
public:
bool isSymmetric(TreeNode *root) {
if(!root)
{
return true;
}
return is_sub_symm(root->left, root->right);
}
};
SECOND TRIAL
class Solution {
private:
bool isSame(TreeNode* p, TreeNode* q)
{
if(!p)
return !q;
else if(!q)
return false;
return p->val == q->val && isSame(p->left, q->right) && isSame(p->right, q->left);
}
public:
bool isSymmetric(TreeNode *root) {
if(!root)
return true;
return isSame(root->left, root->right);
}
};