Description
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:
- The tree will have between 1 and 100 nodes.
分析
题目的意思是:判断一颗树是否是完全二叉树,这道题我写了一下递归,就是ac不了,看了一下答案,计数的方式可以判断,还是蛮奇特的,我说一下思路,每个节点的编号都是固定的,通过父结点能够推算出子节点的编号,这样我跟遍历到的节点都可以赋予一个编号,并加入到数组中,看最后是否等于数组的长度,相等则说明是完全二叉树,不想等则不是。
代码
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def isCompleteTree(self, root: TreeNode) -> bool:
nodes=[(root,1)]
i=0
while(i<len(nodes)):
node,v=nodes[i]
i+=1
if(node):
nodes.append((node.left,2*v))
nodes.append((node.right,2*v+1))
return nodes[-1][1]==len(nodes)