【leetcode 二叉树 C++】110. Balanced Binary Tree

110. Balanced Binary Tree

【leetcode 二叉树 C++】110. Balanced Binary Tree_第1张图片

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    bool flag = true;
    int getHeight(TreeNode* root) {
        if(!root) return 0;
        int l_height = getHeight(root->left);
        int r_height = getHeight(root->right);
        if(abs(l_height - r_height) > 1) {
            flag = false;
            return 0;
        }
        return 1 + max(l_height, r_height);
    }
    bool isBalanced(TreeNode* root) {
        if(!root) return true;
        getHeight(root);
        return flag;
    }
};

你可能感兴趣的:(leetcode,二叉树,leetcode,算法)