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
判断一棵二叉树是否是镜像的
C++(15ms):
1 /** 2 * Definition for a binary tree node. 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */ 10 class Solution { 11 public: 12 bool isSymmetric(TreeNode* root) { 13 TreeNode* left ; 14 TreeNode* right ; 15 if (!root) 16 return true ; 17 queue<TreeNode*> q1 , q2 ; 18 q1.push(root->left) ; 19 q2.push(root->right) ; 20 while(!q1.empty() && !q2.empty()){ 21 left = q1.front() ; 22 q1.pop() ; 23 right = q2.front() ; 24 q2.pop() ; 25 26 if (left == NULL && right == NULL) 27 continue ; 28 if (left == NULL || right == NULL) 29 return false ; 30 if (left->val != right->val) 31 return false ; 32 q1.push(left->left) ; 33 q1.push(left->right) ; 34 q2.push(right->right) ; 35 q2.push(right->left) ; 36 } 37 return true ; 38 } 39 };