My C++ solution in 15ms


  • 12
    B
    class Solution {
    	public:
    		int height(TreeNode *root) {
    			if(root == NULL)return 0;
    			return max(height(root->left), height(root->right)) + 1;
    		}
    		bool isBalanced(TreeNode* root) {
    			if(root == NULL)return true;
    			return isBalanced(root->left) && isBalanced(root->right) && abs(height(root->left) - height(root->right)) <= 1;
    		}
    };

  • 0
    W

    if you change the order of abs and isBalanced function,you will get a better performance。maybe return abs(height(root->left) - height(root->right)) <= 1 && isBalanced(root->left) && isBalanced(root->right) is better


  • 0
    B

    Well no.
    Have you tried? Puting the abs forward results 20ms, 16ms, and the original version results in 15ms, 16ms.
    It's seems because the test cases are too weak...


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.