Leetcode:110. 平衡二叉树

别来无恙 提交于 2020-02-24 09:30:53

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);
    }
};
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!