Balanced Binary Tree
class Solution { public: int depth(TreeNode* root) { if(!root) return 0; int nleft=depth(root->left); int nright=depth(root->right); return (nleft>nright)?(nleft+1):(nright+1); } bool isBalanced(TreeNode* root) { if(!root) return true; int leftdepth=depth(root->left); int rightdepth=depth(root->right); if(leftdepth-rightdepth>1||leftdepth-rightdepth<-1) return false; return isBalanced(root->left)&&isBalanced(root->right); } };
class Solution { public: bool ifBalanced(TreeNode* root,int* depth) { if(!root) { *depth=0; return true; } int left, right; if(ifBalanced(root->left,&left)&&ifBalanced(root->right,&right)) { if(left-right>=-1&&left-right<=1) { *depth=1+(left>right?left:right); return true; } } return false; } bool isBalanced(TreeNode* root) { int depth=0; return ifBalanced(root,&depth); } };