题目链接:https://leetcode.com/problems/balanced-binary-tree/#/description
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: bool isBalanced(TreeNode* root) { if(checkDepth(root)==-1) return false; else return true; } // 计算节点层数,并判断是否为平衡树 int checkDepth(TreeNode* root){ if(root==NULL) return 0; // 左儿子节点层数 int l=checkDepth(root->left); if(l==-1) return -1; // 右儿子节点层数 int r=checkDepth(root->right); if(r==-1) return -1; // 判断是否平衡 int diff=abs(l-r); if(diff>1) return -1; // 返回最大层数 return 1+max(l,r); } };