From 18ba70884914ed10944da16d60bba1fda610262f Mon Sep 17 00:00:00 2001 From: Arthur Date: Thu, 4 Nov 2021 10:56:41 +0000 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=E8=BF=AD?= =?UTF-8?q?=E4=BB=A3=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0110.平衡二叉树.md | 63 ++++++++++++++++++++++++++++++++ 1 file changed, 63 insertions(+) diff --git a/problems/0110.平衡二叉树.md b/problems/0110.平衡二叉树.md index 2e8c239f..f3d70a5c 100644 --- a/problems/0110.平衡二叉树.md +++ b/problems/0110.平衡二叉树.md @@ -666,6 +666,69 @@ bool isBalanced(struct TreeNode* root) { } ``` +迭代法: +```c +//计算结点深度 +int getDepth(struct TreeNode* node) { + struct TreeNode** stack = (struct TreeNode**)malloc(sizeof(struct TreeNode*) * 10000); + int stackTop = 0; + if(node) + stack[stackTop++] = node; + int result = 0; + int depth = 0; + + while(stackTop) { + struct TreeNode* tempNode = stack[--stackTop]; + if(tempNode) { + depth++; + stack[stackTop++] = tempNode; + stack[stackTop++] = NULL; + if(tempNode->left) + stack[stackTop++] = tempNode->left; + if(tempNode->right) + stack[stackTop++] = tempNode->right; + result = result > depth ? result : depth; + } + else { + tempNode = stack[--stackTop]; + depth--; + } + } + + return result; +} + +bool isBalanced(struct TreeNode* root){ + //开辟栈空间 + struct TreeNode** stack = (struct TreeNode**)malloc(sizeof(struct TreeNode*) * 10000); + int stackTop = 0; + + //若根节点不存在,返回True + if(!root) + return 1; + + //将根节点入栈 + stack[stackTop++] = root; + //当栈中有元素时,进行遍历 + while(stackTop) { + //将栈顶元素出栈 + struct TreeNode* node = stack[--stackTop]; + //计算左右子树的深度 + int diff = getDepth(node->right) - getDepth(node->left); + //若深度的绝对值大于1,返回False + if(diff > 1 || diff < -1) + return 0; + //如果栈顶结点有左右结点,将左右结点入栈 + if(node->left) + stack[stackTop++] = node->left; + if(node->right) + stack[stackTop++] = node->right; + } + //若二叉树遍历结束后没有返回False,则返回True + return 1; +} +``` + ----------------------- * 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw) * B站视频:[代码随想录](https://space.bilibili.com/525438321)