添加 0110.平衡二叉树.md C语言递归法

This commit is contained in:
ArthurP
2021-11-03 23:20:18 +01:00
parent d39a7287a2
commit 0d5c3c34de

View File

@ -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) * 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw)