题解 | #二叉搜索树#
二叉搜索树
https://www.nowcoder.com/practice/3d6dd9a58d5246f29f71683346bb8f1b
判断根据输入序列生成的二叉搜索树是否相同
该题的主要思想:二叉排序树相同则对应的前序遍历输出相同
关键点:
- 掌握利用插入法构建二叉排序数
- 二叉排序树相同则对应的前序遍历输出相同
#include<iostream> /* 该题的主要思想:二叉排序树相同则对应的前序遍历输出相同 @keypoints: 1.掌握利用插入法构建二叉排序数 2.二叉排序树相同则对应的前序遍历输出相同 */ using namespace std; struct TreeNode{ TreeNode* lchild; TreeNode* rchild; int data; }; TreeNode* Insert(TreeNode* root,char x){ if(root == nullptr){ root = new TreeNode; root->data = x - '0'; } else{ if(x-'0'data) root->lchild = Insert(root->lchild,x); else root->rchild = Insert(root->rchild, x); } return root; } TreeNode* creatTree(string& s){ TreeNode* node = nullptr; for(int i = 0;i<s.size();++i){ node = Insert(node,s[i]); } return node; } void predOrder(TreeNode* root,string& s){ if(root!=nullptr){ s += root->data + '0'; predOrder(root->lchild, s); predOrder(root->rchild, s); } } int main(){ int n; while(cin >> n){ if(n == 0) break; string target_tree; cin >> target_tree; TreeNode* root = creatTree(target_tree); string target_pred; predOrder(root, target_pred); // cout << target_pred << endl; for(int i = 0;i<n;i++){ cin >> target_tree; TreeNode* temp = creatTree(target_tree); string temp_pred; predOrder(temp, temp_pred); if(temp_pred == target_pred) cout << "YES" <<endl; else cout << "NO" <<endl; } } return 0; }