QR16. BST判定
描述
判断给定的二叉树是否为二分查找树。假设树的每个节点以整数为键值,且不同节点的键值互不相等。二分查找树成立的判定条件:
对任何非叶子节点A,如果A存在左子树,则A的键值大于其左子树所有节点的键值,且,如果A存在右子树,则A的键值小于其右子树所有节点的键值
输入描述
第一行:根节点键值;输出描述
判断结果,0表示输入不是二分查找树,1表示输入是二分查找树示例1
输入:
5 5:4|7 4:3|8 7:2|-1 3:-1|-1 8:-1|-1 2:-1|-1
输出:
0
C++ 解法, 执行用时: 2ms, 内存消耗: 404KB, 提交时间: 2020-11-01
#include<bits/stdc++.h> using namespace std; struct BinaryTree{ int data; BinaryTree *lchild,*rchild; BinaryTree(int data):data(data),lchild(NULL),rchild(NULL){} }; void fun(BinaryTree *root,vector<int> &vec){ if(root){ fun(root->lchild,vec); vec.push_back(root->data); fun(root->rchild,vec); } } int main() { int x; cin>>x; BinaryTree *root=new BinaryTree(x); map<int,BinaryTree*> mapp; mapp[x]=root; int a,b,c; while(scanf("%d:%d|%d",&a,&b,&c)!=EOF){ if(mapp.find(a)!=mapp.end()){ BinaryTree *temp=mapp[a]; if(b!=-1){ temp->lchild=new BinaryTree(b); mapp[b]=temp->lchild; } if(c!=-1){ temp->rchild=new BinaryTree(c); mapp[c]=temp->rchild; } } } vector<int> vec; fun(root,vec); for(int i=1;i<vec.size();i++){ if(vec[i-1]>vec[i]){ cout<<"0"; return 0; } } cout<<"1"; return 0; }
C++ 解法, 执行用时: 2ms, 内存消耗: 424KB, 提交时间: 2021-09-15
#include <bits/stdc++.h> using namespace std; vector<int> v; int res = 1; struct TreeNode { int val; TreeNode* left; TreeNode* right; TreeNode() {} TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} }; void dfs(TreeNode* node) { if (node == nullptr) return; dfs(node->left); if (!v.empty()) { if (v[v.size() - 1] > node->val) { res = 0; return; } } v.push_back(node->val); dfs(node->right); } int isBST(TreeNode* root) { dfs(root); return res; } int main() { int rootVal; cin >> rootVal; unordered_map<int, TreeNode*> m; m[rootVal] = new TreeNode(rootVal); int nodeVal, leftVal, rightVal; // string str_line; // while (getline(cin, str_line)) { // stringstream ss(str_line); // string strNodeVal; // getline(ss, strNodeVal, ':'); // int nodeVal = stoi(strNodeVal); // string strleftVal; // getline(ss, strleftVal, '|'); // int leftVal = stoi(strleftVal); // string strrightVal; // getline(ss, strrightVal, '\n'); // int rightVal = stoi(strrightVal); // if (!m.count(nodeVal)) { // m[nodeVal] = new TreeNode(nodeVal); // } // if (leftVal != -1) { // if (!m.count(leftVal)) m[leftVal] = new TreeNode(leftVal); // m[nodeVal]->left = m[leftVal]; // } // if (rightVal != -1) { // if (!m.count(rightVal)) m[rightVal] = new TreeNode(rightVal); // m[nodeVal]->right = m[rightVal]; // } // } while (scanf("%d:%d|%d", &nodeVal, &leftVal, &rightVal) != EOF) { if (!m.count(nodeVal)) { m[nodeVal] = new TreeNode(nodeVal); } if (leftVal != -1) { if (!m.count(leftVal)) m[leftVal] = new TreeNode(leftVal); m[nodeVal]->left = m[leftVal]; } if (rightVal != -1) { if (!m.count(rightVal)) m[rightVal] = new TreeNode(rightVal); m[nodeVal]->right = m[rightVal]; } if (cin.get() == '\n') if (cin.peek() == '\n') break; } TreeNode *root = m[rootVal]; cout << isBST(root) << endl; return 0; }