From 0d5c3c34de875f845e324ed1772ec3e0db521bbd Mon Sep 17 00:00:00 2001 From: ArthurP Date: Wed, 3 Nov 2021 23:20:18 +0100 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=200110.=E5=B9=B3=E8=A1=A1?= =?UTF-8?q?=E4=BA=8C=E5=8F=89=E6=A0=91.md=20C=E8=AF=AD=E8=A8=80=E9=80=92?= =?UTF-8?q?=E5=BD=92=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0110.平衡二叉树.md | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/problems/0110.平衡二叉树.md b/problems/0110.平衡二叉树.md index 43a49758..e22a12b3 100644 --- a/problems/0110.平衡二叉树.md +++ b/problems/0110.平衡二叉树.md @@ -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)