原题:
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
Note:
Bonus points if you could solve it both recursively and iteratively.
我的思路是移动,然后递归
代码如下:
bool isSymmetric(struct TreeNode* root) {
if(root==NULL)
return true;
if(root->left==NULL&&root->right==NULL)
return true;
if(root->left==NULL||root->right==NULL)
return false;
if(root->left->val==root->right->val)
{
struct TreeNode *p;
p=root->left->left;
root->left->left=root->right->left;
root->right->left=p;
if((isSymmetric(root->left)==false)||isSymmetric(root->right)==false)
return false;
else
return true;
}
return false;
}
效率值:
还可以吧,看了下别人写的,大部分也都是递归,只不过递归的方式不太一样。