A binary tree is strict when all nodes have either two or zero child nodes. The following binary tree is an example of a strict binary tree:
Here are the algorithmic steps to check if a binary tree is strict:
- A null node is a strict tree.
- If the current node has exactly one child node, the tree is not strict.
- If the current node has zero or two child nodes, then the tree is strict if both left and right child nodes are strict. The Java code looks like this:
The Java code looks like this:
public Boolean isStrictTree(TreeNode node) {
if (node == null) {
return true;
}
if ((node.left() == null && node.right() != null) || (node.left() != null && node.right() == null)) {
return false;
}
return isStrictTree(node.left()) && isStrictTree(node.right());
}
You can play around with the code here.