题解 | #判断一棵二叉树是否为搜索二叉树和完全二叉树#
判断一棵二叉树是否为搜索二叉树和完全二叉树
http://www.nowcoder.com/practice/f31fc6d3caf24e7f8b4deb5cd9b5fa97
public:
/**
*
* @param root TreeNode类 the root
* @return bool布尔型vector
*/
bool isSearchBiTree(TreeNode* root, int low, int high)
{
if(!root) return true;
if(root->val <= low || root->val >= high) return false;
return isSearchBiTree(root->left,low,root->val) && isSearchBiTree(root->right, root->val,high);
}
bool isSearchBiTree(TreeNode* root)
{
return isSearchBiTree(root,INT_MIN, INT_MAX);
}
bool isCompleteBiTree(TreeNode* root)
{
if(!root) return true;
queue<TreeNode*> qu;
qu.push(root);
TreeNode* cur;
while(qu.front())
{
cur = qu.front();
qu.pop();
qu.push(cur->left);
qu.push(cur->right);
}
while(!qu.empty()&& qu.front() == nullptr) qu.pop();//如果是完全二叉树,空节点后面应该都是空节点,那么将后面的空节点输出后应该为空
return qu.empty();
}
vector<bool> judgeIt(TreeNode* root) { //参考大佬的Java代码的C++实现
// write code here
vector<bool> rst;
rst.emplace_back(isSearchBiTree(root)); //效率比push_back略高
rst.emplace_back(isCompleteBiTree(root));
return rst;
}