题解 | #二叉搜索树#
二叉搜索树
http://www.nowcoder.com/practice/3d6dd9a58d5246f29f71683346bb8f1b
核心代码:judgeSameBinaryTree函数
#include <iostream>
#include <string>
#include <vector>
#include <stdlib.h>
using namespace std;
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int _val) : val(_val), left(NULL), right(NULL) { }
};
TreeNode* createBinaryTree(TreeNode* root, int data) {
if (root == NULL) {
TreeNode* node = new TreeNode(data);
return node;
}
if (data < root->val) {
root->left = createBinaryTree(root->left, data);
}
else {
root->right = createBinaryTree(root->right, data);
}
return root;
}
bool judgeSameBiTree(TreeNode* root1, TreeNode* root2) {
if (!root1 && !root2) return true;
if (root1 && root2 && root1->val == root2->val) {
return judgeSameBiTree(root1->left, root2->left) && judgeSameBiTree(root1->right, root2->right);
}
else {
return false;
}
}
int main() {
int N;
cin >> N;
string s1;
cin >> s1;
TreeNode* root = NULL;
for(int i = 0; i < s1.size(); i++) {
root = createBinaryTree(root, s1[i]-'0');
}
TreeNode* root2 = NULL;
while (N--) {
string s2;
cin >> s2;
for(int i = 0; i < s2.size(); i++) {
root2 = createBinaryTree(root2, s2[i]-'0');
}
bool flag = judgeSameBiTree(root, root2);
if (flag == true) cout << "YES" << endl;
else cout << "NO" << endl;
root2 = NULL;
}
return 0;
}