LeetCode lc110.平衡二叉树

1. 题目地址:https://leetcode-cn.com/problems/balanced-binary-tree/

2. 题目分析:【1】平衡二叉树:整棵树中每个节点的左右子树高度差绝对值不超过1

【2】由此可以利用递归方法实现解答,先实现一个 function height 计算每个节点的高度,而后使用它计算每个节点左右子树的高度差绝对值.

var isBalanced = function(root) {
  if (!root) {
    return true;
  } 
  return Math.abs(height(root.left) - height(root.right)) <= 1 
      && isBalanced(root.left) && isBalanced(root.right);
};
function height(root) {
  if (!root) {
    return 0;
  } 
  return Math.max(height(root.left), height(root.right)) + 1;
}

 

posted @ 2021-09-27 21:27  TwinkleG  Views(26)  Comments(0)    收藏  举报