Determine whether a tree is a complete binary tree

Insert picture description here

Problem-solving ideas

Perform the following operations in a loop

Insert picture description here

Implementation code

Implementation code 2

public boolean isComplete() {
    
    
		if (root == null) return false;
		Queue<Node<E>> queue = new LinkedList<>();
		queue.offer(root);
		
		boolean leaf = false;
		while (!queue.isEmpty()) {
    
    
			Node<E> node = queue.poll();
			if (leaf && !node.isLeaf()) return false;

			if (node.left != null) {
    
    
				queue.offer(node.left);
			} else if (node.right != null) {
    
    
				return false;
			}
			
			if (node.right != null) {
    
    
				queue.offer(node.right);
			} else {
    
     // 后面遍历的节点都必须是叶子节点
				leaf = true;
			}
		}
		
		return true;
	}
	

Guess you like

Origin blog.csdn.net/pjh88/article/details/114759346