构建二叉树

发布时间:2023年12月30日

二叉树深度:

#include <iostream>
#include <vector>
#include <cmath>
#include <sstream>

using namespace std;

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

// 创建二叉树
TreeNode* createTree(const vector<string>& nodes, int index) {
    if (index >= nodes.size() || nodes[index] == "null") {
        return nullptr;
    }

    int val = stoi(nodes[index]);
    TreeNode* root = new TreeNode(val);
    root->left = createTree(nodes, 2 * index + 1);
    root->right = createTree(nodes, 2 * index + 2);

    return root;
}

// 计算树的高度
int getHeight(TreeNode* root) {
    if (root == nullptr) {
        return 0;
    }

    int leftHeight = getHeight(root->left);
    int rightHeight = getHeight(root->right);

    return 1 + max(leftHeight, rightHeight);
}

// 判断是否是平衡二叉树
bool isBalanced(TreeNode* root) {
    if (root == nullptr) {
        return true;
    }

    int leftHeight = getHeight(root->left);
    int rightHeight = getHeight(root->right);

    if (abs(leftHeight - rightHeight) <= 1 && isBalanced(root->left) && isBalanced(root->right)) {
        return true;
    }

    return false;
}

int main() {
    freopen("in.txt","r",stdin);
    freopen("out.txt","w",stdout);
    string input;
    getline(cin, input);
    stringstream ss(input);
    vector<string> nodes;
    string node;
    while (ss >> node) {
        nodes.push_back(node);
    }

    TreeNode* root = createTree(nodes, 0);

    bool balanced = isBalanced(root);

    if (balanced) {
        cout << "True" << endl;
    }
    else {
        cout << "False" << endl;
    }

    return 0;
}

文章来源:https://blog.csdn.net/2202_76009199/article/details/135309745
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。