class Solution {
public:
vector<TreeNode*> getChilds(vector<TreeNode*>& fathers, bool& isEnd)
{
vector<TreeNode*> ret;
for(int i = 0; i < (int) fathers.size(); i++)
{
if(fathers[i] == NULL) continue;
if(fathers[i]->left)
{
isEnd = false;
ret.push_back(fathers[i]->left);
}
else
{
ret.push_back(NULL);
}
if(fathers[i]->right)
{
isEnd = false;
ret.push_back(fathers[i]->right);
}
else
{
ret.push_back(NULL);
}
}
return ret;
}
bool check(vector<TreeNode*>& left, vector<TreeNode*>& right)
{
if(left.size() != right.size()) return false;
int i, j;
for(i = 0, j = left.size() - 1; i < (int)left.size() && j >= 0; i++, j--)
{
if(left[i] == NULL && right[j] == NULL) continue;
if(left[i] == NULL && right[j] != NULL) return false;
if(left[i] != NULL && right[j] == NULL) return false;
if(left[i]->val != right[j]->val) return false;
}
return true;
}
bool isSymmetric(TreeNode* root)
{
if(!root) return true;
if((!root->left && root->right) || (root->left && !root->right)) return false;
bool ret = true;
vector<TreeNode*> lfathers, rfathers;
lfathers.push_back(root->left);
rfathers.push_back(root->right);
while(ret)
{
if(!check(lfathers, rfathers)) return false;
bool lend = true;
bool rend = true;
vector<TreeNode*> lchilds = getChilds(lfathers, lend);
vector<TreeNode*> rchilds = getChilds(rfathers, rend);
if(lend != rend) return false;
if(lend == true && rend == true) break;
lfathers.clear();
rfathers.clear();
lfathers.assign(lchilds.begin(), lchilds.end());
rfathers.assign(rchilds.begin(), rchilds.end());
}
return ret;
}
};