递归
1 /** 2 * Definition for binary tree 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */ 10 class Solution { 11 public: 12 bool isBalanced(TreeNode *root) { 13 pair<bool,int> res = isOk(root); 14 return res.first; 15 } 16 pair<bool,int> isOk(TreeNode *root){ 17 if(root == NULL){ 18 return make_pair(true,0); 19 } 20 pair<bool,int> left = isOk(root->left); 21 pair<bool,int> right = isOk(root->right); 22 bool balanced = left.first&&right.first; 23 if(abs(left.second-right.second) > 1){ 24 balanced = false; 25 } 26 int height = max(left.second,right.second)+1; 27 return make_pair(balanced,height); 28 } 29 };