101. Symmetric Tree
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
代码如下:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
//思路:
//1.判断root是否为空,若空则返回true,否则false;
//2.判断root->left,root->right是否同时为空,若为空则返回true;
//3.判断root->left,root->right同时不为空时,将root->right反转,
//然后判断新root->right和root->left是否为相同的树。
class Solution {
public:
bool isSameTree(TreeNode* p, TreeNode* q) {
bool childResult;
if( NULL == p && NULL == q)
return true;
if( NULL != p && NULL != q && p->val == q->val)
{
return childResult = isSameTree(p->left,q->left) && isSameTree(p->right,q->right);
}
return false;
}
void reverseTree(TreeNode* root)
{
if(!root)
return;
TreeNode *p,*q;
p = root->left;
q = root->right;
root->left = q;
root->right = p;
reverseTree(root->left);
reverseTree(root->right);
}
bool isSymmetric(TreeNode* root) {
if( (NULL == root) || ( NULL == root->left && NULL == root->right) )
return true;
if(NULL != root->left && NULL != root->right)
{
reverseTree(root->right);
return isSameTree(root->left,root->right);
}
return false;
}
};
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。