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.
算法1:递归解法,判断左右两颗子树是否对称,只要两颗子树的根节点值相同,并且左边子树的左子树和右边子树饿右子树对称 且 左边子树的右子树和右边子树的左子树对称 本文地址
1 /** 2 * Definition for binary tree 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 // IMPORTANT: Please reset any member data you declared, as 14 // the same Solution instance will be reused for each test case. 15 if(root == NULL)return true; 16 return isSymmetricRecur(root->left, root->right); 17 } 18 bool isSymmetricRecur(TreeNode *root1, TreeNode *root2) 19 { 20 if(root1 != NULL && root2 != NULL) 21 { 22 if(root1->val == root2->val && 23 isSymmetricRecur(root1->left, root2->right) && 24 isSymmetricRecur(root1->right, root2->left)) 25 return true; 26 else return false; 27 28 } 29 else if(root1 != NULL || root2 != NULL) 30 return false; 31 else return true; 32 33 } 34 };
算法2:非递归解法,用两个队列分别保存左子树节点和右子树节点,每次从两个队列中分别取出元素,如果两个元素的值相等,则继续把他们的左右节点加入左右队列。要注意每次取出的两个元素,左队列元素的左孩子要和右队列元素的右孩子要同时不为空或者同时为空,否则不可能对称,同理左队列元素的右孩子要和右队列元素的左孩子也一样。
1 /** 2 * Definition for binary tree 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 // IMPORTANT: Please reset any member data you declared, as 14 // the same Solution instance will be reused for each test case. 15 if(root == NULL)return true; 16 queue<TreeNode*> qleft, qright; 17 if(root->left)qleft.push(root->left); 18 if(root->right)qright.push(root->right); 19 while(qleft.empty() == false && qright.empty() == false) 20 { 21 TreeNode *ql = qleft.front(); 22 TreeNode *qr = qright.front(); 23 qleft.pop(); qright.pop(); 24 if(ql->val == qr->val) 25 { 26 if(ql->left && qr->right) 27 { 28 qleft.push(ql->left); 29 qright.push(qr->right); 30 } 31 else if(ql->left || qr->right) 32 return false; 33 if(qr->left && ql->right) 34 { 35 qleft.push(qr->left); 36 qright.push(ql->right); 37 } 38 else if(qr->left || ql->right) 39 return false; 40 } 41 else return false; 42 } 43 if(qleft.empty() && qright.empty()) 44 return true; 45 else return false; 46 } 47 };
【版权声明】转载请注明出处:http://www.cnblogs.com/TenosDoIt/p/3440729.html