LeetCode110. Balanced Binary Tree

    xiaoxiao2025-09-13  173

    问题描述:

    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即可。

    AC代码如下:

    int TreeDepth(TreeNode * root) { if(root == NULL) return 0; int left = TreeDepth(root->left); int right = TreeDepth(root->right); return (left>right?left+1:right+1); } bool isBalanced(TreeNode* root) { if(root == NULL) return true; int left = TreeDepth(root->left); int right = TreeDepth(root->right); int diff = abs(left-right); if(diff > 1) return false; return isBalanced(root->left) && isBalanced(root->right); }

    转载请注明原文地址: https://ju.6miu.com/read-1302606.html
    最新回复(0)