data-structures - 为什么这个检查平衡二叉树的实现是错误的
问题描述
public boolean isBalanced(TreeNode root) {
if(root == null) return true;
int rightCount = maxDepth(root.right);
int leftCount = maxDepth(root.left);
if(Math.abs(rightCount-leftCount)<=1) return true;
return false;
}
public int maxDepth(TreeNode root){
if(root == null) return 0;
return Math.max(maxDepth(root.left),maxDepth(root.right))+1;
}
检查两个分支的最大深度并确定绝对值是否 <=1
解决方案
首先:
如果您有无效的根参数isBalanced
返回true
,那么这是一个糟糕的实现,尽管代码可能没有错误。
在我看来,函数应该使用有效的参数,否则抛出异常(错误?)。
还要检查这个解决方案,阅读代码并尝试做这样的事情:
/* C program to check if a tree is height-balanced or not */
#include <stdio.h>
#include <stdlib.h>
#define bool int
/* A binary tree node has data, pointer to left child
and a pointer to right child */
struct node {
int data;
struct node* left;
struct node* right;
};
/* Returns the height of a binary tree */
int height(struct node* node);
/* Returns true if binary tree with root as root is height-balanced */
bool isBalanced(struct node* root)
{
int lh; /* for height of left subtree */
int rh; /* for height of right subtree */
/* If tree is empty then return true */
if (root == NULL)
return 1;
/* Get the height of left and right sub trees */
lh = height(root->left);
rh = height(root->right);
if (abs(lh - rh) <= 1 && isBalanced(root->left) && isBalanced(root->right))
return 1;
/* If we reach here then tree is not height-balanced */
return 0;
}
/* UTILITY FUNCTIONS TO TEST isBalanced() FUNCTION */
/* returns maximum of two integers */
int max(int a, int b)
{
return (a >= b) ? a : b;
}
/* The function Compute the "height" of a tree. Height is the
number of nodes along the longest path from the root node
down to the farthest leaf node.*/
int height(struct node* node)
{
/* base case tree is empty */
if (node == NULL)
return 0;
/* If tree is not empty then height = 1 + max of left
height and right heights */
return 1 + max(height(node->left), height(node->right));
}
/* Helper function that allocates a new node with the
given data and NULL left and right pointers. */
struct node* newNode(int data)
{
struct node* node = (struct node*)
malloc(sizeof(struct node));
node->data = data;
node->left = NULL;
node->right = NULL;
return (node);
}
int main()
{
struct node* root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);
root->left->left->left = newNode(8);
if (isBalanced(root))
printf("Tree is balanced");
else
printf("Tree is not balanced");
getchar();
return 0;
}
(从这里复制并粘贴)
推荐阅读
- multithreading - 如何量化竞争条件。假设我在一个程序中有 20 个线程,并且出现了 10 次竞态条件
- android - ArrayList 不会填充 ListView 但我可以显示添加到 ArrayList 的项目
- java - 基于请求标识符的客户端请求工厂
- java - 如何测试 util 检测 OS 类
- jmeter - 我需要使用 Json 路径提取器而不是使用 Regex 来获取令牌 id 的值
- azure-devops - 如何将 VSTS 工件复制到 Azure 存储帐户容器文件夹?
- apache-flink - 使用 Apache Flink 自定义水印
- python - 将@Risk 中的 Log Normal 和 Log Normal 截断模拟转换为 Python
- excel - 将单元格引用为索引的公式不起作用
- azure - 为什么 Azure Cosmos DB 需要这么长时间才能删除?