#include<iostream>
#include<vector>
#include<queue>
#include<cmath>
using namespace std;
class TreeNode {
public:
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int value) : val(value), left(nullptr), right(nullptr) {
}
};
TreeNode* BulidTreeNode(vector<int>& vec, int index) {
if (index >= vec.size() || vec[index] == -1) {
return nullptr;
}
TreeNode* root = new TreeNode(vec[index]);
root->left = BulidTreeNode(vec, index * 2 + 1);
root->right = BulidTreeNode(vec, index * 2 + 2);
return root;
}
void MidSearch(TreeNode* root) {
if (root == nullptr) {
return;
}
MidSearch(root->left);
cout << root->val << endl;
MidSearch(root->right);
}
// 层序遍历二叉树
void BFS(TreeNode* root) {
bool leaf = false;
TreeNode* l = root;
TreeNode* r = root;
queue<TreeNode* > que;
que.push(root);
while (!que.empty()) {
for (int i = 0; i < que.size(); i++) {
TreeNode* temp = que.front();
cout << temp->val << endl;
que.pop();
if (temp->left) {
que.push(temp->left);
}
if (temp->right) {
que.push(temp->right);
}
}
}
}
bool IsBSearsh(TreeNode* root) {
bool leaf = false;
TreeNode* l = root;
TreeNode* r = root;
queue<TreeNode* > que;
que.push(root);
while (!que.empty()) {
for (int i = 0; i < que.size(); i++) {
TreeNode* tmp = que.front();
que.pop();
if (tmp->left) {
que.push(tmp->left);
}
if (tmp->right) {
que.push(tmp->right);
}
if (
(leaf && !(l == nullptr && r == nullptr))
||
(l == nullptr && r != nullptr)
) {
return false;
}
if (l == nullptr && r == nullptr) {
leaf = true;
}
}
}
return true;
}
int TreeHeight(TreeNode* root) {
if (root == nullptr) {
return 0;
}
return max(TreeHeight(root->left), TreeHeight(root->right)) + 1;
}
bool IsBalance(TreeNode* root) {
if (root == nullptr) {
return true;
}
int leftHeight = TreeHeight(root->left);
int rightHeight = TreeHeight(root->right);
if (
abs(leftHeight - rightHeight)
&&
IsBalance(root->left)
&&
IsBalance(root->right)) {
return true;
}
}
int MaxDepth(TreeNode* root) {
if (root == nullptr) {
return 0;
}
return max(MaxDepth(root->left), MaxDepth(root->right)) + 1;
}
int main() {
int n;
cin >> n;
vector<int> vec;
for (int i = 0; i < n; i++) {
int num;
cin >> num;
vec.push_back(num);
}
TreeNode* root = BulidTreeNode(vec, 0);
//MidSearch(root);
//BFS(root);
//bool res = IsBSearsh(root);
//bool res = IsBalance(root);
int res;
res = MaxDepth(root);
cout << res << endl;
return 0;
}
标签:right,TreeNode,int,nullptr,que,二叉树,深度,平衡,root
From: https://blog.csdn.net/2401_82661391/article/details/142030463