题目
描述
给定一棵二叉树,已知其中的节点没有重复值,请判断该二叉树是否为搜索二叉树和完全二叉树。
输出描述:分别输出是否为搜索二叉树、完全二叉树。
数据范围:二叉树节点数满足 0≤n≤500000 ,二叉树上的值满足
0≤val≤100000
要求:空间复杂度 O(n),时间复杂度 O(n)
注意:空子树我们认为同时符合搜索二叉树和完全二叉树。
思路
判断是不是搜索二叉树,采用中序遍历,判断遍历结果是不是升序,不是升序就不是搜索二叉树,完全二叉树采用层次遍历的方法,如果遇到了空结点,那之后就只能是空结点,否则就不是完全二叉树。
搜索二叉树:对于每个结点,左子树上的所有结点小于它,右子树上的所有结点大于它。
完全二叉树:结点序列和满二叉树一样,满二叉树是完全二叉树的一种特例。
代码
python版本:
无
c++版本:
/**
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
class Solution {
public:
/**
*
* @param root TreeNode类 the root
* @return bool布尔型vector
*/
vector<bool> judgeIt(TreeNode* root) {
// write code here
vector<bool> res(2, true);
if(root==nullptr){
return res;
}
this->issearchtree(root, res);
this->iscompletetree(root, res);
return res;
}
void issearchtree(TreeNode* root, vector<bool> &res){
if(root==nullptr){
return;
}
vector<int> inorderres;
this->inorder(root, inorderres);
//判断中序遍历结果是否升序
for(int i=0; i<inorderres.size()-1; i++){
if(inorderres[i]>=inorderres[i+1]){
res[0] = false;
break;
}
}
}
void inorder(TreeNode* root, vector<int> & inorderres){
if(root==nullptr){
return;
}
inorder(root->left,inorderres);
inorderres.push_back(root->val);
inorder(root->right,inorderres);
}
void iscompletetree(TreeNode* root, vector<bool> &res){
//层次遍历
queue<TreeNode*> storage;
storage.push(root);
bool flag = false;
while(!storage.empty()){
int node_num = storage.size();
for(int i=0; i<node_num; i++){
TreeNode* node = storage.front();
storage.pop();
if(node==nullptr){
flag = true;
}else{
if(flag){
res[1] = false;
}else{
storage.push(node->left);
storage.push(node->right);
}
}
}
}
}
};