1.二叉树结构体
struct TreeNode
{
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
2.二叉树初始化
TreeNode* initBTree(vector<int> elements)
{
int eleSize;
eleSize = elements.size();
if (eleSize < 1)
{
return NULL;
}
TreeNode **nodes = new TreeNode*[eleSize];
for (int i = 0; i < eleSize; i++)
{
if (elements[i] == 0)
{
nodes[i] = NULL;
}
else
{
nodes[i] = new TreeNode(elements[i]);
}
}
queue<TreeNode*> nodeQueue;
nodeQueue.push(nodes[0]);
TreeNode *node;
int index = 1;
while (index < eleSize)
{
node = nodeQueue.front();
nodeQueue.pop();
nodeQueue.push(nodes[index++]);
node->left = nodeQueue.back();
nodeQueue.push(nodes[index++]);
node->right = nodeQueue.back();
}
return nodes[0];
}
3.二叉树对称性判断
bool isCheak(TreeNode* p, TreeNode* q)
{
if (!p && !q) return true;
if (!p || !q) return false;
return p->val == q->val && isCheak(p->left, p->right) && isCheak(p->right, p->left);
}
bool isSymmetric(TreeNode* root)
{
return isCheak(root, root);
}
4.测试程序
void testIsSymmetric101()
{
vector<int> arr = { 1, 2, 2, 3, 4, 4, 3 };
TreeNode* root = initBTree(arr);
Solution101 sol;
bool result = sol.isSymmetric(root);
cout << "result = " << result << endl;
}```