原題
檢查一棵二叉樹是不是完全二叉樹。完全二叉樹是指一棵樹除了最后一層,其它層上節點都有左右孩子,最后一層上,所有節點都必須盡量靠左。
樣例
1
/ \
2 3
/
4
是完全二叉樹
1
/ \
2 3
\
4
不是完全二叉樹
解題思路
- 理清思路:
- 滿二叉樹:每個節點都有0或是2個孩子。
- 完全二叉樹:所有的葉子都擁有同的深度,所有的內部節點擁有 2個孩子
- BFS - 廣度優先搜索,對于一棵樹,層層遍歷,把每層的節點從左向右依此加入Stack,然后把Stack上層的
None
彈出,最后檢查如果Stack中還有None
說明不是Complete Tree - 比如上面的不完全二叉樹生成的數組為[1, 2, 3, None, 4, None, None],將右側None彈出后為[1, 2, 3, None, 4],循環查找,發現還有None存在,所以是不完全二叉樹
完整代碼
"""
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
this.val = val
this.left, this.right = None, None
"""
class Solution:
"""
@param root, the root of binary tree.
@return true if it is a complete binary tree, or false.
"""
def isComplete(self, root):
# Write your code here
if not root:
return True
list = [root]
index = 0
while index < len(list):
if list[index]:
list.append(list[index].left)
list.append(list[index].right)
index += 1
while list[-1] is None:
list.pop()
for node in list:
if node is None:
return False
return True