【Binary Tree Exercise】 - Balanced Binary Tree

topic description

Description
Given a binary tree, determine whether it is height balanced.
Height-balanced binary tree: the absolute value of the height difference between the left and right subtrees of each node of a binary tree does not exceed 1


Problem solving analysis:

Idea: Divide and conquer algorithm
1. The root node of the current tree is located in a tree that does not meet the conditions of a balanced binary tree, return false, and do not judge later 2. The
root node of the current tree is located in a tree that meets the conditions of a balanced binary tree, and then check the left, Whether the right subtree is satisfied, (the left and right subtrees continue to be decomposed into the above two steps)
continue to be decomposed, judge whether the root node of the current tree meets the conditions of a balanced binary tree, and then check whether the left and right subtrees meet


Code:

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <math.h>
struct TreeNode
{
    
    
	struct TreeNode* left;//节点的左子树
	struct TreeNode* right;//节点的右子树
	int data;//节点的值
};
int maxDepth(struct TreeNode* root)//注意:root表示节点指针,第一次调用指根节点
{
    
    
	if (root == NULL)
	{
    
    
		return 0;
	}
	int leftDepth = maxDepth(root->left);
	int rightDepth = maxDepth(root->right);
	return leftDepth > rightDepth ? leftDepth + 1 : rightDepth + 1;
}
bool isBalancedTree(struct TreeNode* root)//注意:root表示节点指针,第一次调用指根节点
{
    
    
	//空树满足
	if (root == NULL)
		return true;
	int leftDepth = maxDepth(root->left);//计算左子树深度
	int rightDepth = maxDepth(root->right);//计算右子树深度

	return abs(leftDepth - rightDepth) < 2 
		&& isBalancedTree(root->left) && isBalancedTree(root->right);//根(当前节点) 当前节点的左子树 当前节点的右子树

	//abs(leftDepth - rightDepth)是检查当前节点是否满足平衡二叉树的要求,
	//当满足继续递归左子树和右子树isBalancedTree(root->left) && isBalancedTree(root->right)...
	//直到所有的子树都检查了一遍满足要求。
}
//注意:画递归展开图进行理解。

int main()
{
    
    
	//测试功能
	struct TreeNode node1;
	struct TreeNode node2;
	struct TreeNode node3;
	node1.data = 1;
	node1.left = &node2;
	node1.right = &node3;

	node2.data = 2;
	node2.left = NULL;
	node2.right = NULL;

	node3.data = 3;
	node3.left = NULL;
	node3.right = NULL;

	if (isBalancedTree(&node1))
		printf("Yes");
	else
		printf("No");
	return 0;
}

Guess you like

Origin blog.csdn.net/qq_48163964/article/details/130149878