二叉树深度:
#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;
}