Java—Determine whether a tree is a complete binary tree
Idea : Use breadth-first traversal for a complete binary tree, starting from the root node and entering the queue, if the queue is not empty, loop. When you encounter the first node without a left or right son, set the flag bit. If you encounter a node with a left or right son later, then this is not a complete binary tree. This method needs to traverse the entire tree, the complexity is O(N), and N is the total number of nodes.
code show as below:
/**
* @Author shall潇
* @Date 2021/3/4
* @Description
*/
public class CompleteTreeChecker {
class Node { //创建二叉树的数据结构
int data;
Node left;
Node right;
}
//实现广度遍历需要的队列
private LinkedList<Node> queue = new LinkedList<Node>();
//第n层最右节点的标志
private boolean leftMost = false;
public boolean processChild(Node child) {
if(child != null) {
if(!leftMost) {
queue.addLast(child);
} else {
return false;
}
} else {
leftMost = true;
}
return true;
}
public boolean isCompleteTree(Node root) {
//空树也是完全二叉树
if(root == null) return true;
//首先根节点入队列
queue.addLast(root);
while(!queue.isEmpty()) {
Node node = queue.removeFirst();
//处理左子结点
if(!processChild(node.left))
return false;
//处理右子结点
if(!processChild(node.right))
return false;
}
//广度优先遍历完毕,此树是完全二叉树
return true;
}
}