您的位置:首页 > 其它

leetcode[101]:Symmetric Tree

2015-06-18 16:08 369 查看
Symmetric Tree

Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).



Note:

Bonus points if you could solve it both recursively and iteratively.

/**
* Definition for a binary tree node.
* struct TreeNode {
*     int val;
*     struct TreeNode *left;
*     struct TreeNode *right;
* };
*/

bool compare(struct TreeNode* Tleft,struct TreeNode* Tright){

if(Tleft->val != Tright->val ) return false;
if(Tleft->left && !Tright->right || !Tleft->left && Tright->right || Tleft->right && !Tright->left ||!Tleft->right && Tright->left) return false;
if(Tleft->left && Tright->right ) if(!compare(Tleft->left,Tright->right)) return false;
if(Tleft->right && Tright->left ) if(!compare(Tleft->right,Tright->left)) return false;

return true;

}

bool isSymmetric(struct TreeNode* root) {
if(!root) return true;
if(!root->left && !root->right) return true;
if(root->left && root->right) return compare(root->left,root->right);
else return false;
}


根节点单独判断,后面的只需要判断左子树的左子树和右子树的右子树以及左子树的右子树和右子树的左子树即可。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  binary