leetcode543. 二叉树的直径
二叉搜索树
http://www.nowcoder.com/practice/3d6dd9a58d5246f29f71683346bb8f1b
leetcode543. 二叉树的直径
#include<vector>
using namespace std;
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int x) :val(x), left(nullptr), right(nullptr){}
};
TreeNode* insertBST(TreeNode* root, int x) {
if (root == nullptr) {
root = new TreeNode(x);
return root;
}
if (x < root->val) {
root->left = insertBST(root->left, x);
}
else if (x > root->val) {
root->right = insertBST(root->right, x);
}
return root;
}
bool isSameBst(TreeNode* root1, TreeNode* root2) {
if (root1 == nullptr && root2 == nullptr) {
return true;
}
else if ((root1 == nullptr && root2 != nullptr) || (root1 != nullptr && root2 == nullptr)) {
return false;
}
int val1 = root1->val;
int val2 = root2->val;
if (val1 != val2)
return false;
if (isSameBst(root1->left, root2->left) == false || isSameBst(root1->right, root2->right) == false) {
return false;
}
return true;
}
int main() {
int n;
cin >> n;
string str;
cin >> str;
TreeNode* root1 = nullptr;
//1. build BST
for (int i = 0; i < str.size(); i++) {
root1 = insertBST(root1, (int)str[i]);
}
//2. 判断新序列是否为二叉树
for (int i = 0; i < n; i++) {
string s;
cin >> s;
TreeNode* root2 = nullptr;
for (int i = 0; i < s.size(); i++) {
root2 = insertBST(root2, (int)s[i]);
}
if (isSameBst(root1, root2)) {
cout << "YES" << endl;
}
else {
cout << "NO" << endl;
}
}
return 0;
}