【题目描述】
如果二叉树的左右子树的结构是对称的,即两棵子树皆为空,或者皆不空,则称该二叉树是对称的。编程判断给定的二叉树是否对称.
例:如下图中的二叉树T1是对称的,T2是不对称的。
二叉树用顺序结构给出,若读到#则为空,二叉树T1=ABCDE,T2=ABCD#E,如果二叉树是对称的,输出“Yes”,反之输出“No”。
【输入】
二叉树用顺序结构给出,若读到#则为空。
【输出】
如果二叉树是对称的,输出“Yes”,反之输出“No”。
【输入样例】
ABCDE
【输出样例】
Yes
#include <bits/stdc++.h> using namespace std; struct Node { char value; Node *left, *right; }; Node *CreateTree(const string &s, int i) { if (i < 0 || i >= s.size() || s[i] == '#') { return NULL; } else { // cout << i << endl; Node *root = new Node; root->value = s[i]; root->left = root->right = NULL; root->left = CreateTree(s, i * 2 + 1); root->right = CreateTree(s, i * 2 + 2); return root; } } string PreOrder(Node *root) { string s; if (root != NULL) { s.push_back(root->value); s += PreOrder(root->left); s += PreOrder(root->right); } return s; } string InOrder(Node *root) { string s; if (root != NULL) { s += InOrder(root->left); s.push_back(root->value); s += InOrder(root->right); } return s; } string PostOrder(Node *root) { string s; if (root != NULL) { s += PostOrder(root->left); s += PostOrder(root->right); s.push_back(root->value); } return s; } bool sym(Node *root) { if (root == NULL) { return true; } else if (!sym(root->left)) { return false; } else if (!sym(root->right)) { return false; } else if (root->left == NULL && root->right == NULL) { return true; } else if (root->left != NULL && root->right != NULL) { return true; } else { return false; } } int main() { // freopen("1.txt", "r", stdin); string s = "ABCDE"; cin >> s; Node *root = CreateTree(s, 0); // cout << PreOrder(root) << endl; // cout << InOrder(root) << endl; // cout << PostOrder(root) << endl; cout << (sym(root) ? "Yes" : "No"); return 0; }