A PHP Error was encountered

Severity: 8192

Message: str_replace(): Passing null to parameter #3 ($subject) of type array|string is deprecated

Filename: libraries/Filtered_db.php

Line Number: 23

Write a method that checks if a binary tree is perfect
Q:

Write a method that checks if a binary tree is perfect

0

Perfect Binary Tree Check

A binary tree is perfect when all levels are complete.
Write a method that checks if a binary tree is perfect.
TreeNode API methods: node.left() and node.right().

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

public Boolean isPerfectTree(TreeNode node) {
 int treeDepth = depth(node);
    return isPerfectTree(node, 1, treeDepth);
}

private int depth(TreeNode node) {
    return node.left() != null ? 1 + depth(node.left()) : 1;
}

private Boolean isPerfectTree(TreeNode node, int depth, int treeDepth) {
    // check for last level node
    if (depth == treeDepth && (node.left() == null && node.right() == null)) {
        return true;
    }
    // check for inner levels
    if ((node.left() != null && node.right() != null)) {
        return isPerfectTree(node.left(), 1 + depth, treeDepth) &&
                isPerfectTree(node.right(), 1 + depth, treeDepth);
    }
    return false;
}

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now