958. Check Completeness of a Binary Tree

Given the root of a binary tree, determine if it is a complete binary tree.

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: root = [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: root = [1,2,3,4,5,null,7]
Output: false
Explanation: The node with value 7 isn't as far left as possible.

From: https://leetcode.com/problems/check-completeness-of-a-binary-tree/discuss/205682/JavaC%2B%2BPython-BFS-Solution-and-DFS-Soluiton

Use BFS to do a level order traversal,
add childrens to the bfs queue,
until we met the first empty node.

For a complete binary tree,
there should not be any node after we met an empty one.

 1 class Solution {
 2     public boolean isCompleteTree(TreeNode root) {
 3         Queue<TreeNode> bfs = new LinkedList<TreeNode>();
 4         bfs.offer(root);
 5         while (bfs.peek() != null) {
 6             TreeNode node = bfs.poll();
 7             bfs.offer(node.left);
 8             bfs.offer(node.right);
 9         }
10         while (!bfs.isEmpty() && bfs.peek() == null)
11             bfs.poll();
12         return bfs.isEmpty();
13     }
14 }

 

posted @ 2021-03-29 01:08  北叶青藤  阅读(36)  评论(0编辑  收藏  举报