码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode:110. 平衡二叉树

时间:2020-02-24 09:23:09      阅读:64      评论:0      收藏:0      [点我收藏+]

标签:ems   als   代码   solution   log   class   init   max   problems   

Leetcode:110. 平衡二叉树

Leetcode:110. 平衡二叉树

点链接就能看到原题啦~

关于AVL的判断函数写法,请跳转:平衡二叉树的判断

废话不说直接上代码吧~主要的解析的都在上面的链接里了

自顶向下写法

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

自底向上写法

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

Leetcode:110. 平衡二叉树

标签:ems   als   代码   solution   log   class   init   max   problems   

原文地址:https://www.cnblogs.com/cell-coder/p/12355522.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!