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);
    }
};

Balanced Binary Tree - LeetCode

小结

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

相关文章:

  • 2021-11-25
  • 2021-08-27
  • 2022-03-08
  • 2021-11-06
  • 2021-12-22
  • 2021-06-26
  • 2022-12-23
猜你喜欢
  • 2021-09-10
  • 2022-02-04
  • 2022-02-04
  • 2021-10-11
  • 2022-02-18
  • 2021-12-01
  • 2021-05-29
相关资源
相似解决方案