作者: 负雪明烛
id: fuxuemingzhu
个人博客: http://fuxuemingzhu.cn/


题目地址:https://leetcode.com/problems/check-completeness-of-a-binary-tree/

题目描述

Given a binary tree, determine if it is a complete binary tree.

Definition of a complete binary tree from Wikipedia:

  • In a complete binary tree every level, except possibly the last, is completely filled, and all nodes in the last level are as far left as possible. It can have between 1 and 2h nodes inclusive at the last level h.

Example 1:

Input: [1,2,3,4,5,6]
Output: true
Explanation: Every level before the last is full (ie. levels with node-values {1} and {2, 3}), and all nodes in the last level ({4, 5, 6}) are as far left as possible.

Example 2:

Input: [1,2,3,4,5,null,7]
Output: false
Explanation: The node with value 7 isn't as far left as possible.

Note:

  1. The tree will have between 1 and 100 nodes.

题目大意

判断一个二叉树是不是完全二叉树。

解题方法

BFS

这个题可以使用DFS或者BFS先找出二叉树的层次遍历。之后的判断中,使用DFS比较麻烦一些。

使用BFS的话层次遍历比较简单,因为我们从每层的从左到右进行遍历,如果某一层已经出现None之后,后面还有非空叶子节点的话,那么就不是完全二叉树。

代码如下:

# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None class Solution(object):
def isCompleteTree(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
if not root: return True
res = []
que = collections.deque()
que.append(root)
hasNone = False
while que:
size = len(que)
for i in range(size):
node = que.popleft()
if not node:
hasNone = True
continue
if hasNone:
return False
que.append(node.left)
que.append(node.right)
return True

C++代码如下:

/**
* 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:
bool isCompleteTree(TreeNode* root) {
queue<TreeNode*> q;
q.push(root);
while (!q.empty()) {
TreeNode* node = q.front(); q.pop();
if (!node) break;
q.push(node->left);
q.push(node->right);
}
while (!q.empty()) {
TreeNode* node = q.front(); q.pop();
if (node)
return false;
}
return true;
}
};

DFS

思路是,除了最后一层之外,其余的层必须都是满二叉树,最后一层左边只能全部是非空叶子节点,如果出现None之后,后面不能再有非空叶子节点了。

# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None class Solution(object):
def isCompleteTree(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
if not root: return True
res = []
self.getlevel(res, 0, root)
depth = len(res) - 1
for d in range(depth):
if d != depth - 1:
if None in res[d] or len(res[d]) != (2 ** d):
return False
else:
ni = -1
for i, n in enumerate(res[d]):
if n == None:
if ni == -1:
ni = i
else:
if ni != -1:
return False
return True def getlevel(self, res, level, root):
if level >= len(res):
res.append([])
if not root:
res[level].append(None)
else:
res[level].append(root.val)
self.getlevel(res, level + 1, root.left)
self.getlevel(res, level + 1, root.right)

日期

2018 年 12 月 16 日 —— 周赛好难

【LeetCode】958. Check Completeness of a Binary Tree 解题报告(Python & C++)的更多相关文章

  1. leetcode 958. Check Completeness of a Binary Tree 判断是否是完全二叉树 、222. Count Complete Tree Nodes

    完全二叉树的定义:若设二叉树的深度为h,除第 h 层外,其它各层 (1-h-1) 的结点数都达到最大个数,第 h 层所有的结点都连续集中在最左边,这就是完全二叉树. 解题思路:将树按照层进行遍历,如果 ...

  2. LeetCode 958. Check Completeness of a Binary Tree

    原题链接在这里:https://leetcode.com/problems/check-completeness-of-a-binary-tree/ 题目: Given a binary tree, ...

  3. 【LeetCode】297. Serialize and Deserialize Binary Tree 解题报告(Python)

    [LeetCode]297. Serialize and Deserialize Binary Tree 解题报告(Python) 标签: LeetCode 题目地址:https://leetcode ...

  4. 【LeetCode】662. Maximum Width of Binary Tree 解题报告(Python)

    [LeetCode]662. Maximum Width of Binary Tree 解题报告(Python) 标签(空格分隔): LeetCode 题目地址:https://leetcode.co ...

  5. 【leetcode】958. Check Completeness of a Binary Tree

    题目如下: Given a binary tree, determine if it is a complete binary tree. Definition of a complete binar ...

  6. 958. Check Completeness of a Binary Tree

    题目来源 题目来源 C++代码实现 /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode ...

  7. 【LeetCode】111. Minimum Depth of Binary Tree 解题报告(Python)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 DFS BFS 日期 [LeetCode] 题目地址 ...

  8. 【LeetCode】104. Maximum Depth of Binary Tree 解题报告(Python)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 方法一:BFS 方法二:DFS 参考资料 日期 题目 ...

  9. 【LeetCode】979. Distribute Coins in Binary Tree 解题报告(C++)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 递归 日期 题目地址:https://leetcod ...

随机推荐

  1. R语言与医学统计图形-【28】ggplot2扩展包ggrepel、ggsci、gganimate、ggpubr

    ggplot2绘图系统--扩展包ggrepel.ggsci.gganimate.ggpubr等 部分扩展包可在CRAN直接下载,有些需借助devtools包从Github下载. 1. ggrepel包 ...

  2. 前端1 — HTML — 更新完毕

    1.首先来了解一个东西 -- W3C标准( 全称是:World Wide Web Consortium ) 万维网联盟(外语缩写:W3C)标准不是某一个标准,而是一系列标准的集合 -- 这个其实每天都 ...

  3. android studio Please configure Android SDK / please select Android SDK

    有可能是sdk文件损坏造成的. file->settings->appearance&behavior->system settings->android sdk-&g ...

  4. keeper及er表示被动

    一些像employ这样的动词有employer和employee两个名词,而keep的名词只有keeper,keepee不是词.美剧FRIENDS和TBBT里出现了He/she is a keeper ...

  5. 学习Vue源码前的几项必要储备(二)

    7项重要储备 Flow 基本语法 发布/订阅模式 ES6+ 语法 原型链.闭包 函数柯里化 event loop 接上讲 聊到了ES6的几个重要语法,加下来到第四点继续开始. 4.原型链.闭包 原型链 ...

  6. Oracle异常处理——ORA-01502:索引或这类索引的分区处于不可用状态

    Oracle异常处理--ORA-01502:索引或这类索引的分区处于不可用状态参考自:https://www.cnblogs.com/lijiaman/p/9277149.html 1.原因分析经过查 ...

  7. Kotlin 学习(2)

    属性和字段 1.声明属性 Kotlin中可以使用var关键字声明可变属性,或者用val关键字声明只读属性,属性的类型在后面,变量名在前面,中间加冒号和空格. public class Address ...

  8. JavaIO——转换流、字符编码

    1.转换流 转换流是将字节流变成字符流的流. OutputStreamWriter:将字节输出流转换成字符输出流. public class OutputStreamWriter extends Wr ...

  9. JavaIO——File类

    1.File文件类 File类(描述具体文件或文件夹的类):是唯一一个与文件本身操作有关的程序类,可完成文件的创建.删除.取得文件信息等操作.但不能对文件的内容进行修改. (1)File类的基本使用 ...

  10. RAC(Reactive Cocoa)常见的类

    导入ReactiveCocoa框架 在终端,进入Reactive Cocoa文件下 创建podfile 打开该文件 并配置 use_frameworks! pod 'ReactiveCocoa', ' ...