平衡二叉树。给一个二叉树,请你判断它是否是一个平衡二叉树。平衡二叉树的定义是任何两个叶子节点之间的高度差不能大于1。例子,
Example 1:
Given the following tree
[3,9,20,null,null,15,7]
:3 / \ 9 20 / \ 15 7Return true.
Example 2:Given the following tree
[1,2,2,3,3,null,null,4,4]
:1 / \ 2 2 / \ 3 3 / \ 4 4Return false.
这个题的思路是后序遍历。
时间O(n)
空间O(n)
1 /** 2 * @param {TreeNode} root 3 * @return {boolean} 4 */ 5 var isBalanced = function (root) { 6 if (root === null) return true; 7 return helper(root) !== -1; 8 }; 9 10 var helper = function (root) { 11 if (root === null) return 0; 12 let left = helper(root.left); 13 let right = helper(root.right); 14 if (left == -1 || right == -1 || Math.abs(left - right) > 1) { 15 return -1; 16 } 17 return Math.max(left, right) + 1; 18 }