平衡二叉树
题目:输入一棵二叉树,判断该二叉树是否是平衡二叉树。在这里,我们只需要考虑其平衡性,不需要考虑其是不是排序二叉树。平衡二叉树(Balanced Binary Tree),具有以下性质:它是一棵空树或它的左右两个子树的高度差的绝对值不超过1,并且左右两个子树都是一棵平衡二叉树。
思路:后续遍历二叉树。在遍历二叉树每个节点前都会遍历其左右子树。比较左右子树的深度,若差值大于1 则返回一个标记 -1表示当前子树不平衡。左右子树有一个不是平衡的,或左右子树差值大于1,则整课树不平衡。若左右子树平衡,返回当前树的深度(左右子树的深度最大值+1)
代码:
1 /* function TreeNode(x) { 2 this.val = x; 3 this.left = null; 4 this.right = null; 5 } */ 6 function IsBalanced_Solution(pRoot) 7 { 8 // write code here 9 return balanced(pRoot) != -1; 10 } 11 function balanced(node){ 12 if(!node) { 13 return 0; 14 } 15 const left = balanced(node.left); 16 const right = balanced(node.right); 17 if(left == -1 || right == -1 || Math.abs(left - right) > 1){ 18 return -1; 19 } 20 return Math.max(left, right) + 1; 21 } 22 module.exports = { 23 IsBalanced_Solution : IsBalanced_Solution 24 };

浙公网安备 33010602011771号