LeetCode110. 平衡二叉树 [简单]

题目描述:

给定一个二叉树,判断它是否是高度平衡的二叉树。

本题中,一棵高度平衡二叉树定义为:

一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过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:
    int func(TreeNode* root,bool& judge){
        if(root){
            int a=func(root->left,judge);
            int b=func(root->right,judge);
            if(abs(a-b)>1)  judge=false;
            return a>b?a+1:b+1;
        }
        return 0;
    }

    bool isBalanced(TreeNode* root) {
        bool judge=true;
        func(root,judge);
        return judge;
    }
};

发布了66 篇原创文章 · 获赞 1 · 访问量 500

猜你喜欢

转载自blog.csdn.net/qq_41041762/article/details/105158914