Balanced Binary Tree

// isbalanced.cpp : This file contains the 'main' function. Program execution begins and ends there.
//

#include "pch.h"
#include 
#include 

using namespace std;

struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};

class Solution {
public:
    bool isBalanced(TreeNode* root) {
        if (!root) return true;
        if (abs(getTreeDepth(root->left) - getTreeDepth(root->right)) > 1) return false;
        return isBalanced(root->left) && isBalanced(root->right);
    }

    int getTreeDepth(TreeNode* root) {
        if (!root) return 0;
        return 1 + max(getTreeDepth(root->left), getTreeDepth(root->right));
    }
};

int main()
{
    TreeNode* nodes[5] = {
    new TreeNode(3),new TreeNode(9), new TreeNode(20),
    new TreeNode(15), new TreeNode(7)};

    nodes[0]->left = nodes[1];
    nodes[0]->right = nodes[2];

    nodes[2]->left = nodes[3];
    nodes[2]->right = nodes[4];

    Solution s;
    bool balanced = s.isBalanced(nodes[0]);
    cout << balanced << endl;

    for (int i = 4; i >= 0; i--) {
        delete nodes[i];
    }
}


你可能感兴趣的:(Balanced Binary Tree)