crack the code interview 4.1

贝德辉
2023-12-01
//Implement a function to check if a tree is balanced. For the purposes of this question,
//a balanced tree is defined to be a tree such that no two leaf nodes differ in distance
//from the root by more than one.

#include <iostream>
#include <math.h>
using namespace std;

int maxDepth(TreeNode * node)
{
    if (node == NULL)
        return 0;
    return 1 + max(maxDepth(node->left), maxDepth(node->right));
}

int minDepth(TreeNode * node)
{
    if (node == NULL)
        return 0;
    return 1 + min(minDepth(node->left), minDepth(node->right));
}

bool isBalanced(TreeNode * node)
{
    int differ = abs(maxDepth(node), minDepth(node));
    if (differ > 1)
        return false;
    else
        return true;
}

 类似资料:

相关阅读

相关文章

相关问答