The bottom up O(N) solution would be better
This problem is generally believed to have two solutions: the top down approach and the bottom up way.\n\n1.The first method checks whether the tree is balanced
This problem is generally believed to have two solutions: the top down approach and the bottom up way.\n\n1.The first method checks whether the tree is balanced strictly according to the definition of balanced binary tree: the difference between the heights of the two sub trees are not bigger than 1, and both the left sub tree and right sub tree are also balanced. With the helper function depth(), we could easily write the code; \n\n    class solution {\n    public:\n        int depth (TreeNode *root) {\n            if (root == NULL) return 0;\n            return max (depth(root -> left), depth (root -> right)) + 1;\n        }\n    \n        bool isBalanced (TreeNode *root) {\n            if (root == NULL) return true;\n            \n            int left=depth(root->left);\n            int right=depth(root->right);\n            \n            return abs(left - right) <= 1 && isBalanced(root->left) && isBalanced(root->right);\n        }\n    };\n\nFor the current node root, calling depth() for its left and right children actually has to access all of its children, thus the complexity is O(N). We do this for each node in the tree, so the overall complexity of isBalanced will be O(N^2). This is a top down approach.\n\n2.The second method is based on DFS. Instead of calling depth() explicitly for each child node, we return the height of the current node in DFS recursion. When the sub tree of the current node (inclusive) is balanced, the function dfsHeight() returns a non-negative value as the height. Otherwise -1 is returned.  According to the leftHeight and rightHeight of the two children, the parent node could check if the sub tree\nis balanced, and decides its return value.\n\n    class solution {\n    public:\n    int dfsHeight (TreeNode *root) {\n            if (root == NULL) return 0;\n            \n            int leftHeight = dfsHeight (root -> left);\n            if (leftHeight == -1) return -1;\n            int rightHeight = dfsHeight (root -> right);\n            if (rightHeight == -1) return -1;\n            \n            if (abs(leftHeight - rightHeight) > 1)  return -1;\n            return max (leftHeight, rightHeight) + 1;\n        }\n        bool isBalanced(TreeNode *root) {\n            return dfsHeight (root) != -1;\n        }\n    };\n\nIn this bottom up approach, each node in the tree only need to be accessed once. Thus the time complexity is O(N), better than the first solution.
[]