对称的二叉树

题目描述

class Solution {
bool res = true;
public:
bool isSymmetrical(TreeNode* pRoot)
{
if (pRoot == NULL) return true;
isSymmetricalHelper(pRoot->left, pRoot->right);
return res;

}
void isSymmetricalHelper(TreeNode* node_left, TreeNode* node_right)
{
if (node_left == NULL && node_right == NULL) return;
if ((node_left == NULL && node_right != NULL) || (node_left != NULL && node_right == NULL))
{
res = false;
return;
}
if (node_left->val != node_right->val)
{
res = false;
return;
}
isSymmetricalHelper(node_left->left, node_right->right);
isSymmetricalHelper(node_left->right, node_right->left);
}
};

class Solution {
public:
bool isSymmetrical(TreeNode* pRoot)
{
if(pRoot == NULL)
{
return true;
}
queue<TreeNode*> leftTree;
queue<TreeNode*> rightTree;
leftTree.push(pRoot);
rightTree.push(pRoot);
while(leftTree.size() && rightTree.size())
{
TreeNode* tmpLeftNode = leftTree.front();
TreeNode* tmpRightNode = rightTree.front();
if(tmpLeftNode->val != tmpRightNode->val)
{
return false;
}
else
{
leftTree.pop();
rightTree.pop();
//judge left->left and right->right
if(tmpLeftNode->left != NULL && tmpRightNode->right != NULL)
{
leftTree.push(tmpLeftNode->left);
rightTree.push(tmpRightNode->right);
}
else if(tmpLeftNode->left != NULL && tmpRightNode->right == NULL)
{
return false;
}
else if(tmpLeftNode->left == NULL && tmpRightNode->right != NULL)
{
return false;
}
//judge left->right and right->left
if(tmpLeftNode->right != NULL && tmpRightNode->left != NULL)
{
leftTree.push(tmpLeftNode->right);
rightTree.push(tmpRightNode->left);
}
else if(tmpLeftNode->right != NULL && tmpRightNode->left == NULL)
{
return false;
}
else if(tmpLeftNode->right == NULL && tmpRightNode->left != NULL)
{
return false;
}
}
}
if(leftTree.empty() && rightTree.empty())
{
return true;
}
return false;
}
};