标签:
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) {} * }; */ class Solution { public: bool isSymmetric(TreeNode* root) { if(root==NULL)return true; queue<TreeNode*> l; //左子树 queue<TreeNode*> r; //右子树 if(root->left==NULL&&root->right==NULL) return true; else if(root->left!=NULL&&root->right!=NULL) { l.push(root->left); r.push(root->right); } else return false; while(!l.empty()&&!r.empty()) { TreeNode* temp1=l.front(); TreeNode* temp2=r.front(); if(temp1->val!=temp2->val) return false; l.pop(); r.pop(); if(temp1->left&&temp2->right) { l.push(temp1->left); r.push(temp2->right); } else if((temp1->left==NULL^temp2->right==NULL)==1) return false; if(temp1->right&&temp2->left) { l.push(temp1->right); r.push(temp2->left); } else if((temp1->right==NULL^temp2->left==NULL)==1) return false; } if(l.empty()&&r.empty()) return true; else return false; } };
leetcode No101. Symmetric Tree
标签:
原文地址:http://blog.csdn.net/u011391629/article/details/52247811