/** * struct TreeNode { * int val; * struct TreeNode *left; * struct TreeNode *right; * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * }; */ #include <algorithm> class Solution { public: /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param pRoot TreeNode类 * @return bool布尔型 */ bool IsBalanced_Solution(TreeNode* pRoot) { // write code here if(pRoot == nullptr) return true; int l = high(pRoot->left); int r = high(pRoot->right); if(abs(l-r)>1) return false; return (IsBalanced_Solution(pRoot->left)&&IsBalanced_Solution(pRoot->left)); } int high(TreeNode *root){ if(!root) return 0; return max(high(root->left)+1, high(root->right)+1); } };
此题考查递归和二叉树的高度的判断方法。