思想
- 先获得左右子树的最大深度
- 比较左右子树的最大深度
- 返回当前子树最大深度+1的值
代码
int GetTreeDepth(TreeNode* node){
if(!node){
return 0;
}
int left = GetTreeDepth(node->left);
int right = GetTreeDepth(node->right);
//return (left >= right ? left : right) + 1;
return max(left,right) + 1;
}
经典 leetcode 例题
检查树的平衡性
https://leetcode-cn.com/problems/check-balance-lcci/
class Solution {
public:
bool isBalanced(TreeNode* root) {
if(root == NULL)
return true;
int left = GetTreeDepth(root->left);
int right = GetTreeDepth(root->right);
int result = abs(left - right);
return result < 2 && isBalanced(root->left) && isBalanced(root->right);
}
int GetTreeDepth(TreeNode* node){
if(!node){
return 0;
}
int left = GetTreeDepth(node->left);
int right = GetTreeDepth(node->right);
//return (left >= right ? left : right) + 1;
return max(left,right) + 1;
}
};
网友评论