來源:力扣(LeetCode)
連接:https://leetcode-cn.com/problems/check-balance-lcci
著做權歸領釦網絡全部。商業轉載請聯繫官方受權,非商業轉載請註明出處。javascript
實現一個函數,檢查二叉樹是否平衡。在這個問題中,平衡樹的定義以下:任意一個節點,其兩棵子樹的高度差不超過 1。java
示例 1:
給定二叉樹 [3,9,20,null,null,15,7]
3
/ \
9 20
/ \
15 7
返回 true 。
示例 2:
給定二叉樹 [1,2,2,3,3,null,null,4,4]
1
/ \
2 2
/ \
3 3
/ \
4 4
返回 false 。node
/** * Definition for a binary tree node. * function TreeNode(val) { * this.val = val; * this.left = this.right = null; * } */ /** * @param {TreeNode} root * @return {boolean} */ var isBalanced = function(root) { let res = true; function check(root){ if(!root) return 0; if(res === false) return 0; let left = check(root.left); let right = check(root.right); if(Math.abs(left-right) > 1) res = false; return Math.max(left,right)+1; } check(root); return res; };