KS36. 判断一棵满二叉树是否为二叉搜索树
描述
给定一棵满二叉树,判定该树是否为二叉搜索树,是的话打印True,不是的话打印False
输入描述
从根节点开始,逐层输入每个节点的值,空树或空节点输入为None输出描述
是二叉搜索树的话打印True,不是的话打印False示例1
输入:
10,5,15,3,7,13,18
输出:
True
示例2
输入:
None
输出:
True
示例3
输入:
10,5,15,3,4,13,18
输出:
False
说明:
节点值为 5 的左子节点和右子节点是 3 , 4 都小于根节点 5 ,所以不是二叉搜索树C++ 解法, 执行用时: 3ms, 内存消耗: 396KB, 提交时间: 2020-07-16
#include <iostream> #include <vector> using namespace std; struct Node{ int data; int left; int right; Node(int d) { data = d; left = -1; right = -1; } Node(){} }; const int N = 15000; int tmp = -99999; bool isright = true; Node lib[N]; //中序遍历 void mid(Node node){ if(node.left != -1) mid(lib[node.left]); //递归左子树 int data = node.data; if(data > tmp) tmp = data; else { isright = false; } if(node.right != -1) mid(lib[node.right]); } int main() { int firstdata; cin >> firstdata; Node firstNode = Node(firstdata); lib[1] = firstNode; int index =1; int t; //输入结点 while (scanf(",%d",&t)){ Node node(t); index++; lib[index] = node; } int i=1; //更新左右子树的编号。 while(i*2 < index){ lib[i].left = i*2; lib[i].right = i*2+1; i++; } //中序遍历 mid(lib[1]); if(isright){ cout<<"True"<<endl; }else{ cout<<"False"<<endl; } return 0; }
C++ 解法, 执行用时: 3ms, 内存消耗: 436KB, 提交时间: 2020-08-18
#include <stdio.h> #include <vector> #include <queue> bool judge(int* data, int len) { if (!data || len <= 0) { return true; } std::queue<std::pair<int, int> > judges; judges.push(std::make_pair(-1, -1)); for (int i = 0; i < len; ++i) { std::pair<int, int> tmp = judges.front(); judges.pop(); if (tmp.first != -1 && tmp.first >= data[i]) { return false; } if (tmp.second != -1 && tmp.second <= data[i]) { return false; } judges.push(std::make_pair(tmp.first, data[i])); judges.push(std::make_pair(data[i], tmp.second)); } return true; } int main(int argc, char** argv) { std::vector<int> data; while (true) { int tmp = 0; if (scanf("%d", &tmp) != 1) { break; } data.push_back(tmp); if (getchar() == '\n') { break; } } printf("%s\n", judge(&data[0], data.size()) ? "True" : "False"); return 0; }