剑指 Offer 55 - I. 二叉树的深度
class Solution {
public:
int maxDepth(TreeNode* root) {
queue<TreeNode * >q;
q.push(root);
int res = 0;
if(root == NULL)return res;
while(!q.empty()){
int qSize = q.size();
res++;
for(int i = 0; i < qSize; i++){
TreeNode * temp = q.front();
if(temp->left)q.push(temp->left);
if(temp->right)q.push(temp->right);
q.pop();
}
}
return res;
}
};
剑指 Offer 55 - II. 平衡二叉树
题目描述:剑指 Offer 55 - II. 平衡二叉树
题解思路:0110.平衡二叉树
class Solution {
public:
bool isBalanced(TreeNode* root) {
if(root == nullptr)return true;
return bfs(root) == -1 ? false : true;
}
int bfs(TreeNode * node){
if(node == nullptr)return 0;
int left = bfs(node->left);
if(left == -1)return -1;
int right = bfs(node->right);
if(right == -1)return -1;
if(abs(left - right) > 1){
return - 1;
}else{
return max(left, right) + 1;
}
}
};