[LeetCode] Balanced Binary Tree

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.

 
 思路: 后序遍历二叉树。同时判断以该节点为根的子树是否是平衡树。如果是则返回该子树的高度,如果不是返回-1
相关题目:《剑指offer》面试题39
/**
 * 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 == NULL) return true;
        
        if (depth(root) == -1) {
            return false;
        } else {
            return true;
        }
    }
    
    int depth(TreeNode* root) {
        if (root == NULL) return 0;
        
        int left_depth = depth(root->left);
        if (left_depth == -1) return -1;
        int right_depth = depth(root->right);
        if (right_depth == -1) return -1;
        
        if (abs(left_depth - right_depth) > 1) return -1;
        
        return max(left_depth, right_depth) + 1;
    }
    

};
原文地址:https://www.cnblogs.com/vincently/p/4716381.html