|
| 1 | +package com.fishercoder.solutions; |
| 2 | + |
| 3 | +import com.fishercoder.common.classes.TreeNode; |
| 4 | + |
| 5 | +import java.util.LinkedList; |
| 6 | +import java.util.Queue; |
| 7 | + |
| 8 | +/** |
| 9 | + * 958. Check Completeness of a Binary Tree |
| 10 | + * |
| 11 | + * Given a binary tree, determine if it is a complete binary tree. |
| 12 | + * Definition of a complete binary tree from Wikipedia: |
| 13 | + * 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. |
| 14 | + * It can have between 1 and 2h nodes inclusive at the last level h. |
| 15 | + * |
| 16 | + * Example 1: |
| 17 | + * 1 |
| 18 | + * / \ |
| 19 | + * 2 3 |
| 20 | + * / \ / |
| 21 | + * 4 5 6 |
| 22 | + * |
| 23 | + * Input: [1,2,3,4,5,6] |
| 24 | + * Output: true |
| 25 | + * Explanation: Every level before the last is full (ie. levels with node-values {1} and {2, 3}), |
| 26 | + * and all nodes in the last level ({4, 5, 6}) are as far left as possible. |
| 27 | + * |
| 28 | + * Example 2: |
| 29 | + * 1 |
| 30 | + * / \ |
| 31 | + * 2 3 |
| 32 | + * / \ \ |
| 33 | + * 4 5 7 |
| 34 | + * Input: [1,2,3,4,5,null,7] |
| 35 | + * Output: false |
| 36 | + * Explanation: The node with value 7 isn't as far left as possible. |
| 37 | + * |
| 38 | + * Note: |
| 39 | + * The tree will have between 1 and 100 nodes. |
| 40 | + * */ |
| 41 | +public class _958 { |
| 42 | + public static class Solution1 { |
| 43 | + public boolean isCompleteTree(TreeNode root) { |
| 44 | + Queue<TreeNode> queue = new LinkedList<>(); |
| 45 | + queue.offer(root); |
| 46 | + boolean shouldHaveNoMoreChildren = false; |
| 47 | + while (!queue.isEmpty()) { |
| 48 | + int size = queue.size(); |
| 49 | + for (int i = 0; i < size; i++) { |
| 50 | + TreeNode curr = queue.poll(); |
| 51 | + if (shouldHaveNoMoreChildren && (curr.left != null || curr.right != null)) { |
| 52 | + return false; |
| 53 | + } |
| 54 | + if (curr.left == null && curr.right != null) { |
| 55 | + return false; |
| 56 | + } |
| 57 | + if (curr.left != null) { |
| 58 | + queue.offer(curr.left); |
| 59 | + } |
| 60 | + if (curr.right == null) { |
| 61 | + shouldHaveNoMoreChildren = true; |
| 62 | + } else { |
| 63 | + queue.offer(curr.right); |
| 64 | + } |
| 65 | + } |
| 66 | + } |
| 67 | + return true; |
| 68 | + } |
| 69 | + } |
| 70 | +} |
0 commit comments