【LeetCode】平衡二叉树

【问题】给定一个二叉树,判断它是否是高度平衡的二叉树。
本题中,一棵高度平衡二叉树定义为:
一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过1。

示例 1:
给定二叉树 [3,9,20,null,null,15,7]

3
/ \
9 20
/ \
15 7

返回 true

【思路】

对于平衡树来说,其要求是左右子树的深度之差不能大于1,我们使用一个简单的递归思路来解决,当然也可以使用非递归,不过比较复杂!

由于我们需要知道左右子树的深度,那么递归的返回值显然是左右子树的深度,但我们整个主函数是返回一个bool, 因此我们将bool变量flag设置为类中的成员变量,通过递归函数对其值进行更新。

/**
 * 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 res = true;
    int check(TreeNode* node){
        if(node == nullptr)  return 0;
        int l = 1 + check(node->left);
        int r = 1 + check(node->right);
        if(abs(l-r) > 1){
            res = false;
        }
        return max(l, r);
    }

    bool isBalanced(TreeNode* root) {
        check(root);
        return res;
    }
};

猜你喜欢

转载自www.cnblogs.com/zhudingtop/p/11644781.html