您的位置:首页 > 其它

树 Balanced Binary Tree

2015-04-11 21:46 85 查看
思想:

每一节点的左支和右支的深度和不能超过1;

每一节点(作为它父节点的左支或右支)都有一个深度值要返回,以便在其父节点进行平衡判断;

/**
 * Definition for binary tree
 * 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(balancedHeight(root) >= 0) return true;
        else return false;
    }
    int balancedHeight(TreeNode *root) {
        if(root == NULL) return true;
        int left = balancedHeight(root->left);
        int right = balancedHeight(root->right);
        if(left < 0 || right < 0 || abs(left-right) > 1)
            return -1;
        return max(left,right)+1;
    }
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: