平衡二叉树-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;
    }
};

 

已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 编程工作室 设计师:CSDN官方博客 返回首页