这两天都是基础题,又都刚刚复习过,直接默写!
1.二叉树的深度
class Solution {
public:
int getDepth(TreeNode* node){
if(node==NULL) return 0;
//左右中
int leftDepth=getDepth(node->left);
int rightDepth=getDepth(node->right);
return max(leftDepth,rightDepth)+1;
}
int maxDepth(TreeNode* root) {
return getDepth(root);
}
};
2.平衡二叉树
class Solution {
public:
int getHeight(TreeNode* node){
//左右中
if(node==NULL) return 0;
int leftHeight=getHeight(node->left);
int rightHeight=getHeight(node->right);
if(leftHeight==-1||rightHeight==-1) return -1;
if(abs(leftHeight-rightHeight)>1) return -1;
return max(leftHeight,rightHeight)+1;
}
bool isBalanced(TreeNode* root) {
if(root==NULL) return true;
int res=getHeight(root);
return res>0?1:0;
}
};