Given a binary tree, check if it is mirror-symmetrical.
For example, a binary tree [1,2,2,3,4,4,3] is symmetric.
1
/ \
2 2
/ \ / \
3 4 4 3
However, the following [1,2,2, null, 3, null, 3] is not a mirror image:
1
/ \
2 2
\ \
3 3
Description:
If you can use recursion and iteration are two ways to solve this problem would be a plus.
//递归
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
void DFS(struct TreeNode* p,struct TreeNode* q,bool *ret)
{
if(*ret)
{
if((p&&!q)||(!p&&q))
{
*ret=false;
return;
}
if(p&&q)
{
if(p->val!=q->val)
{
*ret=false;
return;
}
else
{
DFS(p->left,q->right,ret);
DFS(p->right,q->left,ret);
}
}
}
}
bool isSymmetric(struct TreeNode* root){
bool ret=true;
if(root)
DFS(root->left,root->right,&ret);
return ret;
}
//迭代
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
bool isSymmetric(struct TreeNode* root){
struct TreeNode**left=NULL;
struct TreeNode**right=NULL;
if(root)
{
int size=1;
left=(struct TreeNode**)malloc(sizeof(struct TreeNode*)*size);
left[0]=root->left;
right=(struct TreeNode**)malloc(sizeof(struct TreeNode*)*size);
right[0]=root->right;
bool all_none=false;
while(!all_none)
{
all_none=true;
int next_size=2*size;
left=(struct TreeNode**)realloc(left,sizeof(struct TreeNode*)*next_size);
right=(struct TreeNode**)realloc(right,sizeof(struct TreeNode*)*next_size);
for(int i=0;i<size;i++)
{
if((left[i]&&!right[i])||(!left[i]&&right[i]))goto END;
if(!left[i]&&!right[i])
{
left[i+size]=NULL;
right[i+size]=NULL;
}
else
{
if(left[i]->val!=right[i]->val)goto END;
left[i+size]=left[i]->right;
left[i]=left[i]->left;
right[i+size]=right[i]->left;
right[i]=right[i]->right;
all_none=false;
}
}
size=next_size;
}
}
free(left);
free(right);
return true;
END:
free(left);
free(right);
return false;
}
Recursion:
When execution: 12 ms, beat the 85.66% of user C in Symmetric Tree of submission
Memory consumption: 8.1 MB, defeated 100.00% of user C in Symmetric Tree of submission
Iteration:
When execution: 80 ms, beat the 5.58% of users in Symmetric Tree of C submission
Memory consumption: 186.9 MB, beat the 5.23% of users in Symmetric Tree of C submission