欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

110. Balanced Binary Tree

程序员文章站 2022-05-18 19:53:04
...

problems:
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.
tips:
判断二叉树是否为高度平衡二叉树,即它的两个子树每个节点的深度之差都不大于1.

solutions:
1.超时,但是逻辑清晰简单,便于理解下一个方法。

class Solution {
public:
    bool isBalanced(TreeNode* root) {
       if(!root) return true;
       if(!isBalanced(root->left)) return false;
       if(!isBalanced(root->right)) return false;
       int left = depth(root->left);
       int right = depth(root->right);
       if(abs(left-right)>1)
           return false;
        return true;
    }
    int depth(TreeNode* root)
    {
        if(!root) return 0;
        return max(depth(root->left),depth(root->right))+1;
    }
};
 class Solution {
    public:
        bool isBalanced(TreeNode* root) {
            return depth(root)!=-1;
        }
        int depth(TreeNode* root)
        {
            if(!root) return 0;
            int left = depth(root->left);
            int right = depth(root->right);
            if(left == -1 || right == -1 || abs(left-right)>1)//不平衡时为-1
                return -1;
            return max(left,right)+1;
        }
    };
相关标签: tree