自底向上的递归,类似于后序遍历,对于当前遍历到的节点,先递归地判断其左右子树是否平衡,再判断以当前节点为根的子树是否平衡。
#include "stdbool.h" #define NULL ((void *)0) //Definition for a binary tree node. struct TreeNode { int val; struct TreeNode *left; struct TreeNode *right; }; int height(struct TreeNode* root) { if (root == NULL) return 0; int leftHeight = height(root->left); int rightHeight = height(root->right); if (leftHeight == -1 || rightHeight == -1 || fabs(leftHeight - rightHeight) > 1) return -1; else return fmax(leftHeight, rightHeight) + 1; } bool isBalanced(struct TreeNode* root) { return height(root) >= 0; }
原文:https://www.cnblogs.com/vicky2021/p/14820217.html