110. Balanced Binary Tree
Leetcode
題目
Input: root = [3,9,20,null,null,15,7]
Output: trueInput: root = [1,2,2,3,3,null,null,4,4]
Output: falseInput: root = []
Output: true解答
Last updated
Input: root = [3,9,20,null,null,15,7]
Output: trueInput: root = [1,2,2,3,3,null,null,4,4]
Output: falseInput: root = []
Output: trueLast updated
const getHeight = function(node) {
if (!node) return 0;
const leftH = getHeight(node.left);
const rightH = getHeight(node.right);
return Math.max(leftH, rightH) + 1;
};
var isBalanced = function(root) {
if (!root) return true;
const leftH = getHeight(root.left);
const rightH = getHeight(root.right);
return Math.abs(leftH - rightH) <= 1 && isBalanced(root.left) && isBalanced(root.right);
};const helper = (node) => {
if (!node) return [true, 0];
const [isLeftBalanced, leftH] = helper(node.left);
if (!isLeftBalanced) return [false, 0];
const [isRightBalanced, rightH] = helper(node.right);
if (!isRightBalanced) return [false, 0];
return [Math.abs(leftH - rightH) <= 1, Math.max(leftH, rightH) + 1]
}
var isBalanced = function(root) {
return helper(root)[0];
};