Balanced Binary Tree - LeetCode

题目链接

Balanced Binary Tree - LeetCode

注意点

  • 不要访问空结点

解法

解法一:getDep用于求各个点深度的,然后对每个节点的两个子树来比较深度差,时间复杂度为O(NlgN)。

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

小结

  • avl的子树高度差不超过1

猜你喜欢

转载自www.cnblogs.com/multhree/p/10586533.html