Code link: https://leetcode.com/problems/balanced-binary-tree/
Note the definition of height and depth might be differnt from the official definition of Wikipedia. In this question, the depth is the number of nodes from root to that spesific node, but not the number of paths.
First we could get the height of a node's left and right subtree, and check if they are balanced. Then we could do this check recursively against current nodes' left and right tree. This is like a top-down way of search.
class Solution { public boolean isBalanced(TreeNode root) { if (root == null) { return true; } int lh = getHeight(root.left); int rh = getHeight(root.right); if (Math.abs(lh - rh) > 1) { return false; } return isBalanced(root.left) && isBalanced(root.right); } private int getHeight(TreeNode root) { if (root == null) { return 0; } return Math.max(getHeight(root.left), getHeight(root.right)) + 1; } }
class Solution { public boolean isBalanced(TreeNode root) { return getHeight(root) != -1; } private int getHeight(TreeNode root) { if (root == null) { return 0; } int lh = getHeight(root.left); int rh = getHeight(root.right); if (lh == -1 || rh == -1 || Math.abs(lh - rh) > 1) { return -1; } return Math.max(lh, rh) + 1; } }
Time: O(n). The method getHeight() is O(n).
Space: O(n).
Similar problem: