leetcode 110. Balanced Binary Tree

解题思路:
递归判断左子树的高度与右子树的高度之差是否大于1

原题目:

Given a binary tree, determine if it is height-balanced.

For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.

AC解,C++代码,菜鸟一个,请大家多多指正

/**
 * 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 treeHeight(TreeNode* root) {
        if (root == NULL) {
            return 0;
        }
        if (root->left == NULL && root->right == NULL) {
            return 1;
        }
        return 1 + max(treeHeight(root->left), treeHeight(root->right));
    }
    bool isBalanced(TreeNode* root) {
        if (root == NULL) {
            return true;
        }

        int diff = treeHeight(root->left) - treeHeight(root->right);
        if (diff >= -1 && diff <= 1) {
            return isBalanced(root->left) && isBalanced(root->right);
        }
        return false;
    }
};

你可能感兴趣的:(leetcode,leetcode,递归)