Leetcode-958 Check Completeness of a Binary Tree(二叉树的完全性检验)

模板题,不懂为什么会比第一题分高

 1 class Solution
 2 {
 3     public:
 4         bool isCompleteTree(TreeNode* root)
 5         {
 6             if (root == NULL)
 7                 return false;
 8 
 9             queue<TreeNode *> q;
10             q.push(root);
11             bool mustHaveNoChild = false;
12             bool result = true;
13             while (!q.empty())
14             {
15                 TreeNode* pNode = q.front();
16                 q.pop();
17                 if (mustHaveNoChild)//如果一个节点没有子节点;只要出现了空子树的节点,后面出现的必须为叶子节点(左字树右子树必须为空)
18                 {
19                     if (pNode->left != NULL || pNode->right != NULL)
20                     {
21                         result = false;
22                         break;
23                     }
24                 }
25                 else
26                 {
27                     if (pNode->left != NULL && pNode->right != NULL)
28                     {
29                         q.push(pNode->left);
30                         q.push(pNode->right);
31                     }
32                     else if (pNode->left != NULL && pNode->right == NULL)
33                     {
34                         mustHaveNoChild = true;
35                         q.push(pNode->left);
36                     }
37                     else if(pNode->left == NULL && pNode->right != NULL)
38                     {
39                         result = false;
40                         break;
41                     }
42                     else
43                     {
44                         mustHaveNoChild = true;
45                     }
46                 }
47             }
48             return result;
49 
50         }
51 };

 

posted @ 2018-12-16 12:25  Asurudo  阅读(301)  评论(0编辑  收藏  举报