首页 > 其他 > 详细

Balanced Binary Tree - LeetCode

时间:2019-03-24 01:21:27      阅读:164      评论:0      收藏:0      [点我收藏+]

题目链接

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

Balanced Binary Tree - LeetCode

原文:https://www.cnblogs.com/multhree/p/10586533.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!