您的位置:首页 > 其它

LeetCode-101. Symmetric Tree

2017-02-28 17:12 363 查看
问题:https://leetcode.com/problems/symmetric-tree/?tab=Description

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

分析:对称树的左右子树也是相互对称的。前一题写过两棵二叉树的等价对吧。那么判断两棵二叉树对称的话,就是把等价算法里面的if(NULL == p || NULL == q ||p->val!=q->val || !isSameTree(p->left,q->left) ||!isSameTree(p->right,q->right) )中的

!isSameTree(p->left,q->left)、!isSameTree(p->right,q->right)

改成 ! isSameTree (p->left,q->right) 、 ! isSameTree(p->right,q->left)

所谓对称,就是对称地等价。

参考C++代码:

/**
* Definition for a binary tree node.
* struct TreeNode {
*     int val;
*     TreeNode *left;
*     TreeNode *right;
*     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool isSymmetric(TreeNode* root) {
if(NULL == root) return true;
if(NULL == root->left && NULL == root->right) return true;
return isMirrorTree(root->left,root->right);
}

bool isMirrorTree(TreeNode* p, TreeNode* q) {
if(NULL == p && NULL == q) return true;
if(NULL == p || NULL == q || p->val!=q->val || !isMirrorTree(p->left,q->right) || !isMirrorTree(p->right,q->left) ) return false;
return true;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  二叉树 ie it leetcode