【leetcode】958. 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.

解题思路:完全二叉树有这个一个定律:完全二叉树中任一节点编号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 = None

class 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)

 

posted @ 2018-12-18 10:41  seyjs  阅读(294)  评论(0编辑  收藏  举报