110. Balanced Binary Tree

来源:互联网 发布:ai软件怎么使用 编辑:程序博客网 时间:2024/06/08 08:06

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.

思路:先计算每个node的高度,然后一层一层的判断是否是balance的。

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

避免重复计算:

/** * 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;        }        calHight(root);        return isSubTreeBalanced(root);    }    bool isSubTreeBalanced(TreeNode *root)    {       if(root==NULL) return true;        int l = 0, r = 0;        if(root->left!=NULL) l = root->left->val;        if(root->right!=NULL) r = root->right->val;        if(abs(l-r) <=1 && isSubTreeBalanced(root->left) && isSubTreeBalanced(root->right))        {            return true;        }        return false;    }    int calHight(TreeNode *root)    {        if(root==NULL)        {            return 0;        }        root->val = 1 + max(calHight(root->left), calHight(root->right));        return root->val;    }};
0 0