标签:
Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
For example, this binary tree is symmetric:
1 / 2 2 / \ / 3 4 4 3
But the following is not:
1 / 2 2 \ 3 3
Note:
Bonus points if you could solve it both recursively and iteratively.
这题类似same tree.
用递归的方法是,在传递参数的时候把东西倒着传递
迭代的方法是,左右子树压进去,每次弹两个,注意压入的顺序
递归:
1 class Solution { 2 public: 3 bool isSymmetric(TreeNode* root) { 4 if (root == NULL) 5 return true; 6 return isMirror(root->left,root->right); 7 } 8 bool isMirror(TreeNode* root1, TreeNode* root2) { 9 if (root1 == NULL && root2 == NULL) 10 return true; 11 if (root1 == NULL || root2 == NULL) 12 return false; 13 return (root1->val == root2->val ) && isMirror(root1->left,root2->right) && isMirror(root1->right,root2->left); 14 } 15 };
迭代:
1 class Solution { 2 public: 3 bool isSymmetric(TreeNode* root) { 4 if (root == NULL) 5 return true; 6 queue <TreeNode* > q; 7 if (root->left) 8 q.push(root->left); 9 if (root->right) 10 q.push(root->right); 11 while(q.size()>=2) { 12 TreeNode* point1 = q.front(); 13 q.pop(); 14 TreeNode* point2 = q.front(); 15 q.pop(); 16 if (point1->val != point2->val) 17 return false; 18 if (point1->left != NULL && point2->right != NULL) 19 { 20 q.push(point1->left); 21 q.push(point2->right); 22 } 23 else if (point1->left == NULL && point2->right != NULL) 24 return false; 25 else if (point1->left != NULL && point2->right == NULL) 26 return false; 27 28 if (point2->left != NULL && point1->right != NULL) 29 { 30 q.push(point2->left); 31 q.push(point1->right); 32 } 33 else if (point2->left == NULL && point1->right != NULL) 34 return false; 35 else if (point2->left != NULL && point1->right == NULL) 36 return false; 37 } 38 if(!q.empty()) 39 return false; 40 return true; 41 } 42 };
标签:
原文地址:http://www.cnblogs.com/zhuguanyu33/p/4587644.html