Idea: I
only talk about the idea of a complete binary tree here. You can read my blog to search for a binary tree, please click!
Complete binary tree can solve the problem according to the following steps:
- Traverse in layer order, traverse all nodes in turn from the left to the right of each layer
- If the current node has a right child node, but no left child node, return false directly
- If the current node does not have all the left and right child nodes, then the following nodes must all be leaf nodes, otherwise it will directly return false
- If false is not returned during the traversal process, it will return true after the traversal is over
Code:
/**
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
class Solution {
public:
vector<bool> judgeIt(TreeNode* root) {
// write code here
vector<bool> res{
true,true};
if (!root) return res;
inOrder(root);
for(int i = 1;i<midSeq.size();++i) //检查是否升序序列
if (midSeq[i] < midSeq[i - 1]) {
res[0] = false;
break;
}
res[1] = isComplete(root);
return res;
}
void inOrder(TreeNode* root) {
//中序遍历
if (root == nullptr) return;
inOrder(root->left);
midSeq.emplace_back(root->val);
inOrder(root->right);
}
bool isComplete(TreeNode* root) {
queue<TreeNode*> q;
q.push(root);
TreeNode* left ,* right;
bool leaf = false;
while(q.size()){
auto it = q.front();
q.pop();
left = it->left;
right = it->right;
if(leaf && (left!=NULL || right!=NULL)) return false;//这种情况只有当leaf为true时才会进行判断
if(left==NULL && right!=NULL) return false;
if(left!=NULL) q.push(left);
if(right!=NULL) q.push(right);
else leaf = true; //表示该节点之后的所有节点应该都是叶子节点才符合完全二叉树的定义。
}
return true;
}
private:
vector<int> midSeq;//中序遍历序列
};