【写在前面】
刷个开心系列,第二篇,选择了同样非常基础的二叉树相关的一道题目。
【原题描述】
Given a binary tree, determine if it is height-balanced.
For this problem, a height-balanced binary tree is defined as:
a binary tree in which the left and right subtrees of every node
differ in height by no more than 1.
【解题思路】
分别利用递归求二叉树的深度和判断是否平衡。
【源代码】
int getDepth(struct TreeNode *root) {
int left, right = 0;
if (root == NULL)
return 0;
else{
left = getDepth(root->left)+1;
right = getDepth(root->right)+1;
}
return left > right ? left : right;
}
bool isBalanced(struct TreeNode *root){
if(root == NULL) return true;
int l_depth = getDepth(root -> left);
int r_depth = getDepth(root -> right);
if(abs(l_depth - r_depth) > 1) return false;
return isBalanced(root -> left) && isBalanced(root -> right);
}