【剑指offer】【树】55-II.平衡二叉树

题目链接:https://leetcode-cn.com/problems/ping-heng-er-cha-shu-lcof/

递归

/**
 * 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;
        if(abs(getHeight(root -> left) - getHeight(root -> right)) > 1) return false;
        return isBalanced(root -> left) && isBalanced(root -> right);
    }
    bool getHeight(TreeNode* root){
        if(!root) return 0;
        int lh = getHeight(root -> left);
        int rh = getHeight(root -> right);
        return lh > rh ? lh + 1 : rh + 1;
    }
};
posted @ 2020-05-06 20:20  NaughtyCoder  阅读(92)  评论(0)    收藏  举报