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 11 12 void dep(TreeNode *root,int *d,int t) 13 { 14 if(root==NULL) 15 { 16 if(t>*d) 17 { 18 *d=t; 19 } 20 } 21 else 22 { 23 dep(root->left,d,t+1); 24 dep(root->right,d,t+1); 25 } 26 } 27 28 class Solution { 29 public: 30 bool isBalanced(TreeNode *root) { 31 // Start typing your C/C++ solution below 32 // DO NOT write int main() function 33 int d1,d2; 34 d1=d2=-1; 35 if(root==NULL) 36 return true; 37 dep(root->left,&d1,0); 38 dep(root->right,&d2,0); 39 if(abs(d1-d2)>1) 40 { 41 return false; 42 } 43 else return isBalanced(root->left)&&isBalanced(root->right); 44 45 } 46 };