完全二叉树的定义:若设二叉树的深度为h,除第 h 层外,其它各层 (1~h-1) 的结点数都达到最大个数,第 h 层所有的结点都连续集中在最左边,这就是完全二叉树。
解题思路:将树按照层进行遍历,如果出现null后还出现非null则能证明这个不是完全二叉树
https://leetcode.com/problems/check-completeness-of-a-binary-tree/discuss/205768/Java-easy-Level-Order-Traversal-one-while-loop
class Solution { public: bool isCompleteTree(TreeNode* root) { bool end = false; if(root == NULL) return true; queue<TreeNode*> q; q.push(root); while(!q.empty()){ TreeNode* node = q.front(); q.pop(); if(node == NULL) end = true; else{ if(end) return false; q.push(node->left); q.push(node->right); } } return true; } };
222. Count Complete Tree Nodes
这题是计算完全二叉树有多少个节点,按照层序遍历,找到第一个为空的节点就停止计算就好了。
注意:将node = q.front()放在循环的末尾,不放在一开始。因为每一次while都需要判断node是否为空,如果放在开始,后面的push操作就会写很多冗余的代码。同时,放在后面的话,也要在循环
外就进行初始化
class Solution { public: int countNodes(TreeNode* root) { int count = 0; queue<TreeNode*> q; q.push(root); TreeNode* node = root; while(node != NULL){ q.pop(); count++; q.push(node->left); q.push(node->right); node = q.front(); } return count; } };
另一种写法,自己的:
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: int countNodes(TreeNode* root) { if(!root) return 0; queue<TreeNode*> q; q.push(root); int count = 0; while(!q.empty()){ TreeNode* tmp = q.top(); if(!tmp) break; count++; q.pop(); q.push(tmp->left); q.push(tmp->right); } return count; } };