题解 | #判断一棵二叉树是否为搜索二叉树和完全二叉树#
判断一棵二叉树是否为搜索二叉树和完全二叉树
http://www.nowcoder.com/practice/f31fc6d3caf24e7f8b4deb5cd9b5fa97
/** * struct TreeNode { * int val; * struct TreeNode *left; * struct TreeNode *right; * }; */ class Solution { public: /** * * @param root TreeNode类 the root * @return bool布尔型vector */ // 判断是不是二叉搜索树(中序遍历) TreeNode* pre = nullptr; bool isSearchTree(TreeNode* root) { if(root == nullptr) return true; if(!isSearchTree(root->left)) return false; if(pre && pre->val >= root->val) return false; pre = root; return isSearchTree(root->right); } // 判断是不是完全二叉树(层序遍历) bool isFullTree(TreeNode* root) { if(root == nullptr) return true; queue<TreeNode*> que; que.emplace(root); bool flag = false; // 出现叶子节点的标记 while(!que.empty()) { auto cur = que.front(); que.pop(); if(cur == nullptr) { // 出现了叶子节点(为空的节点) flag = true; continue; } if(flag) { // 前面出现了叶子节点,而当前节点又不是空 return false; } que.emplace(cur->left); que.emplace(cur->right); } return true; } vector<bool> judgeIt(TreeNode* root) { vector<bool> ans{isSearchTree(root), isFullTree(root)}; return ans; } };