Discription:
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
Solutions:
1. Recursive solution
bool isSymmetric(TreeNode *left, TreeNode *right){
if (!left && !right)
return true;
if (!left || !right)
return false;
if (left->val != right->val)
return false;
return isSymmetric(left->left, right->right) && isSymmetric(left->right, right->left);
}
bool isSymmetric(TreeNode* root) {
if (!root)
return true;
return isSymmetric(root->left, root->right);
}
2. Iteration solution
迭代解法中需要使用栈(也可以使用队列,这里不需要优先处理子树)来保存接下来需要判断的两个结点,这里使用了两个栈,也可以使用一个栈(同时压入两个,同时弹出两个)。
bool isSymmetric(TreeNode* root) { //迭代
if (!root)
return true;
stack<TreeNode*> stack1;
stack<TreeNode*> stack2;
stack1.push(root->left);
stack2.push(root->right);
while (!stack1.empty()){
TreeNode* left = stack1.top();
TreeNode* right = stack2.top();
stack1.pop();
stack2.pop();
if (!left && !right)
continue;
if (!left|| !right )
return false;
else{
if (left->val != right->val)
return false;
else{
stack1.push(left->left);
stack2.push(right->right);
stack1.push(left->right);
stack2.push(right->left);
}
}
}
return true;
}
3. Test
#include<iostream>
#include<stack>
using namespace std;
TreeNode* creatBTree(int data[], int index, int n)
{
TreeNode *pNode = NULL;
if (index < n && data[index]!=-1) //-1令树结点为NULL
{
pNode = new TreeNode(data[index]);
pNode->left = creatBTree(data, 2 * index + 1, n); //将二叉树按照层序遍历, 依次标序号, 从0开始
pNode->right = creatBTree(data, 2 * index + 2, n);
}
return pNode;
}
int main()
{
int a[] = { 2, 3, 3, 4, 5, 5, -1 };
//int a[] = { 1, 2, 2, 3, 4, 4, 3 };
int size = sizeof(a) / sizeof(int);
TreeNode* root = creatBTree(a, 0, size);
cout << isSymmetric(root) << endl;
cin.get();
return 0;
}
GitHub-LeetCode:
https://github.com/wenwu313/LeetCode