题目描述:
递归求解
/** * 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(root == NULL) return true; if(abs(getdeepth(root->right) - getdeepth(root->left)) > 1) return false; return isBalanced(root->right) && isBalanced(root->left); } int getdeepth(TreeNode *node){ if(node == NULL) return 0; int l1 = getdeepth(node->left) + 1; int l2 = getdeepth(node->right) + 1; return max(l1,l2); } };