[牛客网-Leetcode] #树 简单 balanced-binary-tree

二叉平衡树 balanced-binary-tree

题目描述

判断给定的二叉树是否是平衡的
在这个问题中,定义平衡二叉树为每个节点的左右两个子树高度差的绝对值不超过1的二叉树

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.

示例

示例1
输入

{1,#,2,#,3}

输出

flase

示例2
输入

{2,1,3}

输出

true

解题思路

  • 先写一个函数用于计算最大深度,然后对于二叉树的每一个节点,都计算其左子树和右子树的最大深度
  • 剪枝: 如果左右子树深度差大于1,直接返回false,不用继续判断左右子树,只有深度差不大于1时,才继续判断左右子树
/**
 * struct TreeNode {
 *	int val;
 *	struct TreeNode *left;
 *	struct TreeNode *right;
 * };
 */

class Solution {
    
    
public:
    bool isBalanced(TreeNode* root) {
    
    
        if(root == NULL) return true;
        int left = maxDepth(root -> left);   //左子树的最大深度
        int right = maxDepth(root -> right); //右子树的最大深度
        //剪枝:判断当前根节点是否是平衡的,如果不平衡,直接返回false,不用继续判断子树
        if(abs(left - right) > 1) return false;
        return isBalanced(root -> left) && isBalanced(root -> right);
    }
    //求以root为根节点的树的最大深度
    int maxDepth(TreeNode* root) {
    
    
        if(root == NULL) return 0;
        int left = maxDepth(root -> left);
        int right = maxDepth(root -> right);
        return max(left, right) + 1;
    }
};

猜你喜欢

转载自blog.csdn.net/cys975900334/article/details/106817657