Skip to content

110.Balanced Binary Tree

难度Easy

刷题内容

原题连接

  • https://leetcode.com/problems/balanced-binary-tree/

内容描述

Given a binary tree, determine if it is height-balanced.

For this problem, a height-balanced binary tree is defined as:

a binary tree in which the depth of the two subtrees of every node never differ by more than 1.

Example 1:

Given the following tree [3,9,20,null,null,15,7]:

    3
   / \
  9  20
    /  \
   15   7
Return true.

Example 2:

Given the following tree [1,2,2,3,3,null,null,4,4]:

       1
      / \
     2   2
    / \
   3   3
  / \
 4   4
Return false.

˼· **- ʱ�临�Ӷ�: O(n)*- �ռ临�Ӷ�: O(1)***

�ж��и�ƽ内容描述�����ֻҪ内容描述������ĸ߶Ȳ�ж��Ƿ����1���ٷֱ��ж内容描述��Ƿ�Ϊƽ内容描述���

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    bool isBalanced(TreeNode* root) {
        if(root == nullptr)
            return true;
        return abs(height(root ->left) - height(root ->right)) <= 1 && isBalanced(root ->left) && isBalanced(root ->right);
    }
    int height(TreeNode* root){
        if(root == nullptr)
            return 0;
        return max(height(root ->left),height(root ->right)) + 1;
    }
};


回到顶部