algorithm - 平衡二叉树逻辑

标签 algorithm tree binary-tree

问题是确定给定的树(以 A 为根)是否平衡。 我写了这段代码。它在一个测试用例上失败了。 逻辑有什么问题?

int depth(TreeNode* root){
    if (root==NULL) return 0;
    else return max(depth(root->left),depth(root->right))+1;
}
int Solution::isBalanced(TreeNode* A) {
    if(A==NULL) return 1;
    if((abs(depth(A->left)-depth(A->right)))>1) return 0;
    else {
        isBalanced(A->left);
        isBalanced(A->right);
        return 1;
    }
}

最佳答案

您正在丢弃 else 子句中递归调用的结果。尝试这样的事情:

if((abs(depth(A->left) - depth(A->right))) <= 1 && isBalanced(A->left) && isBalanced(A->right)) {
    return 1;
}
else {
    return 0;
}

关于algorithm - 平衡二叉树逻辑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52008795/

相关文章:

c++ - 逐层打印二叉树

c++ - 给定一个二叉搜索树和一个数字,找到一条路径,其节点的数据相加为给定的数字。

arrays - 合并排序数组

java - dijkstra算法的绘图图

algorithm - 为什么这两种关系成立?

c# - RNGCryptoServiceProvider 无法对大随机数进行卡方检验

r - 使用权重向量设置 networkD3 节点大小

clojure - 遍历向量树

algorithm - 从整数流创建平衡二叉搜索树

c++ - 二叉树中的节点为空