博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
【leetcode】958. Check Completeness of a Binary Tree
阅读量:6793 次
发布时间:2019-06-26

本文共 1611 字,大约阅读时间需要 5 分钟。

题目如下:

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

Definition of a complete binary tree from :

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: trueExplanation: 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: falseExplanation: The node with value 7 isn't as far left as possible.
 

Note:

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

解题思路:完全二叉树有这个一个定律:完全二叉树中任一节点编号n,则其左子树为2n,右子树为2n+1。所以,只要遍历一遍二叉树,记根节点的编号为1,依次记录每个遍历过的节点的编号,同时记录编号的最大值MAX。最后判断所有遍历过的节点的编号的和与sum(1~MAX)是否相等即可。

代码如下:

# Definition for a binary tree node.# class TreeNode(object):#     def __init__(self, x):#         self.val = x#         self.left = None#         self.right = Noneclass Solution(object):    number = []    maxNum = 0    def traverse(self,node,seq):        self.maxNum = max(self.maxNum,seq)        self.number.append(seq)        if node.left != None:            self.traverse(node.left,seq*2)        if node.right != None:            self.traverse(node.right,seq*2+1)    def isCompleteTree(self, root):        """        :type root: TreeNode        :rtype: bool        """        self.number = []        self.maxNum = 0        self.traverse(root,1)        return (self.maxNum+1)*self.maxNum/2 == sum(self.number)

 

转载于:https://www.cnblogs.com/seyjs/p/10135695.html

你可能感兴趣的文章
(转)delete和析构函数两者之间的联系
查看>>
常见DOS命令总结
查看>>
间隙锁例子
查看>>
大数据Java基础第十天作业
查看>>
c#日期函数
查看>>
安装XEN
查看>>
共享栈
查看>>
服务器时间同步
查看>>
Keepalived + nginx的安装部署
查看>>
SSH反向代理
查看>>
python数据类型-字符串
查看>>
IT运维之Linux服务器监控方案
查看>>
redis
查看>>
keytool生成证书
查看>>
lvs调度算法
查看>>
java中for循环冒号用法
查看>>
php常用函数总结
查看>>
QEMU-KVM虚机动态迁移原理
查看>>
我的友情链接
查看>>
从码云上clone项目到本地不能纳入管理问题
查看>>