平衡二叉树-2

力扣地址

后序遍历

/**
 * 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 isBalanced(TreeNode* root) {
        if (!root) return true;
        return judge(root) != -1;
    }

    int judge(TreeNode* root) {
        if (!root) return 0;
        int left = judge(root->left);
        if (-1 == left) return -1;
        int right = judge(root->right);
        if (-1 == right) return -1;
        return std::abs(left - right) <= 1 ? std::max(left, right) + 1 : -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:
    bool isBalanced(TreeNode* root) {
        if (!root) return true;
        return std::abs(depth(root->left) - depth(root->right)) <= 1 && isBalanced(root->left) && isBalanced(root->right);
    }

    int depth(TreeNode* root) {
        if (!root) return 0;
        return std::max(depth(root->left), depth(root->right)) + 1;
    }
};

猜你喜欢

转载自blog.csdn.net/TESE_yan/article/details/114274647