mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 16:54:50 +08:00
添加 0110.平衡二叉树.md C语言递归法
This commit is contained in:
@ -619,6 +619,36 @@ var isBalanced = function(root) {
|
||||
};
|
||||
```
|
||||
|
||||
##C
|
||||
递归法:
|
||||
```c
|
||||
int getDepth(struct TreeNode* node) {
|
||||
//如果结点不存在,返回0
|
||||
if(!node)
|
||||
return 0;
|
||||
//求出右子树深度
|
||||
int rightDepth = getDepth(node->right);
|
||||
//求出左子树深度
|
||||
int leftDepth = getDepth(node->left);
|
||||
//返回左右子树中的较大值+1
|
||||
return rightDepth > leftDepth ? rightDepth + 1 : leftDepth + 1;
|
||||
}
|
||||
|
||||
bool isBalanced(struct TreeNode* root) {
|
||||
//递归结束条件为:传入结点为NULL,返回True
|
||||
if(!root)
|
||||
return 1;
|
||||
//求出左右子树的深度
|
||||
int leftDepth = getDepth(root->left);
|
||||
int rightDepth = getDepth(root->right);
|
||||
int diff;
|
||||
//若左右子树绝对值差距大于1,返回False
|
||||
if((diff = leftDepth - rightDepth) > 1 || diff < -1)
|
||||
return 0;
|
||||
//检查左右子树是否为平衡二叉树
|
||||
return isBalanced(root->right) && isBalanced(root->left);
|
||||
}
|
||||
```
|
||||
|
||||
-----------------------
|
||||
* 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw)
|
||||
|
Reference in New Issue
Block a user