Check whether a given Binary Tree is Complete or not 解答

时间:2022-02-05 12:56:54

Question

complete binary tree is a binary tree in which every level, except possibly the last, is completely filled, and all nodes are as far left as possible.

Solution 1 -- BFS

Using BFS and a flag.

 public class Solution {
public boolean checkCompleteBinaryTree(TreeNode root) {
// BFS
// flag whether means previous node has both children
boolean flag = true;
List<TreeNode> current = new ArrayList<TreeNode>();
List<TreeNode> next;
current.add(root); while (current.size() > 0) {
next = new ArrayList<TreeNode>();
for (TreeNode node : current) {
if (!flag && (node.left != null || node.right != null))
return false;
if (node.left == null && node.right != null)
return false;
if (node.left != null) {
next.add(node.left);
if (node.right != null) {
next.add(node.right)
flag = true;
} else {
flag = false;
}
}
}
current = next;
} return true;
}
}

Solution 2 -- Recursive

Using recursion