|
| 1 | +# https://leetcode.com/problems/check-completeness-of-a-binary-tree/ |
| 2 | + |
| 3 | +# Definition for a binary tree node. |
| 4 | +# class TreeNode: |
| 5 | +# def __init__(self, val=0, left=None, right=None): |
| 6 | +# self.val = val |
| 7 | +# self.left = left |
| 8 | +# self.right = right |
| 9 | + |
| 10 | +from collections import deque |
| 11 | + |
| 12 | +class Solution: |
| 13 | + |
| 14 | + def isCompleteTree(self, root: Optional[TreeNode]) -> bool: |
| 15 | + |
| 16 | + """ |
| 17 | + OBJECTIVE: Return true if given binary tree is complete. If not, return false |
| 18 | + |
| 19 | + NOTE: A complete binary tree only has NULL nodes at the bottom, far-right side of the tree. I.e, if a tree has N nodes, then N - 1 nodes can't be null! |
| 20 | + |
| 21 | + Time Complexity: O(n) where n = # of nodes because the tree is being traversed once through breadth-first search |
| 22 | + |
| 23 | + Space Complexity: O(n) where n = # of nodes because all the nodes are being added to a queue during a breadth-first search |
| 24 | + """ |
| 25 | + |
| 26 | + # If root is empty or by itself, return true |
| 27 | + if root is None or (root.left == root.right == None): |
| 28 | + return True |
| 29 | + |
| 30 | + # Use bfs() to traverse tree |
| 31 | + queue = deque([root]) |
| 32 | + discoveredNull = False # <= Create a variable to determine if a None node was discovered |
| 33 | + |
| 34 | + while queue: |
| 35 | + |
| 36 | + # Pop first element from queue |
| 37 | + popped = queue.popleft() |
| 38 | + |
| 39 | + # Check if there's a left child |
| 40 | + if popped.left: |
| 41 | + |
| 42 | + # If a null node was previously discovered, return false |
| 43 | + if discoveredNull: |
| 44 | + return False |
| 45 | + |
| 46 | + # Add left child to queue |
| 47 | + queue.append(popped.left) |
| 48 | + |
| 49 | + # If left child is null, set boolean variable to true |
| 50 | + else: |
| 51 | + discoveredNull = True |
| 52 | + |
| 53 | + # Check if there's a right child |
| 54 | + if popped.right: |
| 55 | + |
| 56 | + # If a null node was previously discovered, return false |
| 57 | + if discoveredNull: |
| 58 | + return False |
| 59 | + |
| 60 | + # Add right child to queue |
| 61 | + queue.append(popped.right) |
| 62 | + |
| 63 | + # If right child is null, set boolean variable to true |
| 64 | + else: |
| 65 | + discoveredNull = True |
| 66 | + |
| 67 | + # If function is still continuing, then tree is complete |
| 68 | + return True |
0 commit comments