您的位置:首页 > 其它

leetcode 101. Symmetric Tree

2017-07-04 09:48 417 查看
原题:

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;
}效率值:

还可以吧,看了下别人写的,大部分也都是递归,只不过递归的方式不太一样。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: