题解 | #判断一棵二叉树是否为搜索二叉树和完全二叉树#
判断一棵二叉树是否为搜索二叉树和完全二叉树
http://www.nowcoder.com/practice/f31fc6d3caf24e7f8b4deb5cd9b5fa97
class Solution { public: /** * * @param root TreeNode类 the root * @return bool布尔型vector */ vector<bool> judgeIt(TreeNode* root) { return {issearch(root),iswhole(root)}; } bool iswhole(TreeNode *root) { if(!root) return true; queue<TreeNode* > q; q.push(root); bool flag=false; while(!q.empty()) { int n=q.size(); while(n--) { TreeNode* p=q.front(); q.pop(); if(p->left) q.push(p->left); if(p->left&&p->right) q.push(p->right); else if(!p->left&&p->right) return false; else if(!p->right) { flag=true; break; } } while(flag&&!q.empty()) { TreeNode* p=q.front(); q.pop(); if(p->left||p->right) return false; } } return true; } bool issearch(TreeNode *root) { if(!root) return true; TreeNode *l,*r; if(root->left) { if(root->val<root->left->val||!issearch(root->left)) return false; l=root->left; while(l->right) l=l->right; if(l->val>root->val) return false; } if(root->right) { if(root->val>root->right->val||!issearch(root->right)) return false; r=root->right; while(r->left) r=r->left; if(r->val<root->val) return false; } return true; } };