class Solution { public: bool isBalanced(TreeNode *root) { if(root==NULL)return true; int left=depth(root->left); int right=depth(root->right); if(abs(left-right)>1)return false; return isBalanced(root->left)&&isBalanced(root->right); } int depth(TreeNode *root) { if(root==NULL)return 0; int left=depth(root->left); int right=depth(root->right); return left>right?left+1:right+1; } };
Max PathSum
class Solution { public: vector<int>v; int maxPathSum(TreeNode *root) { v.clear(); PreOrder(root); int max=v[0]; for(int i=0;i<v.size();i++) { if(max<v[i])max=v[i]; } return max; } void PreOrder(TreeNode *root) { v.push_back(TwomaxSum(root)); if(root->left)PreOrder(root->left); if(root->right)PreOrder(root->right); } int TwomaxSum(TreeNode *root) { if(root==NULL)return 0; int sum=root->val; if(maxSum(root->left)>0)sum+=maxSum(root->left); if(maxSum(root->right)>0)sum+=maxSum(root->right); return sum; } int maxSum(TreeNode *root) { if(root==NULL)return 0; if(root->left==NULL&&root->right==NULL)return root->val; int left=maxSum(root->left); int right=maxSum(root->right); if(left<=0&&right<=0)return root->val; else return left>=right?(left+root->val) :(right+root->val); } };