遞迴判斷是否二叉平衡樹

SmartDemo發表於2020-12-22

 可以說是相當簡潔粗暴了。

#include<iostream>
#include<algorithm>
using namespace std;
struct Node{
    int val;
    Node *left,*right;
    Node(int x):val(x),left(NULL),right(NULL){}
};
int height(Node* root){
    if(root == NULL) return 0;
    return max(height(root->left),height(root->right))+1;
}
int Is_AVL(Node* root){
    if(root == NULL) return 0;
    return abs(height(root->left) - height(root->right)) <= 1;
}

int main(){
    Node* root = new Node(1);
    root->left = new Node(2);
    root->right = new Node(3);
    root->left->left = new Node(4);
    // root->left->left->left = new Node(5);
    cout<<Is_AVL(root);
    return 0;
}

 

相關文章