题目:
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.
/**
* 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(NULL == root) return true;
return isSymetricCore(root->left, root->right);
}
private:
bool isSymetricCore(TreeNode *left, TreeNode *right){
if(NULL == left && NULL == right) return true;
if(NULL == left || NULL == right || left->val != right->val) return false;
return isSymetricCore(left->left, right->right) && isSymetricCore(left->right, right->left);
}
};
非递归实现(方法类似于中序遍历)
/**
* 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 (NULL == root || NULL == root->left && NULL == root->right) return true;
if (NULL == root->left || NULL == root->right) return false;
stack<TreeNode *> leftStack, rightStack;
leftStack.push(root->left);
rightStack.push(root->right);
TreeNode *pLeft = root->left;
TreeNode *pRight = root->right;
while (pLeft && pRight || !leftStack.empty() && !rightStack.empty()){
while (pLeft && pRight){
leftStack.push(pLeft);
rightStack.push(pRight);
pLeft = pLeft->left;
pRight = pRight->right;
}
if (pLeft || pRight) return false;
pLeft = leftStack.top();
pRight = rightStack.top();
leftStack.pop();
rightStack.pop();
if (pLeft->val != pRight->val) return false;
pLeft = pLeft->right;
pRight = pRight->left;
}
if (pLeft || pRight || !leftStack.empty() || !rightStack.empty()) return false;
return true;
}
};