From a1004808796f6b97bd86753e1b9d859ebab4ff09 Mon Sep 17 00:00:00 2001 From: ArthurP Date: Sat, 6 Nov 2021 10:51:37 +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=E8=BF=AD?= =?UTF-8?q?=E4=BB=A3=E6=B3=95=E6=B3=A8=E9=87=8A?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0110.平衡二叉树.md | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/problems/0110.平衡二叉树.md b/problems/0110.平衡二叉树.md index f3d70a5c..b0ecf44a 100644 --- a/problems/0110.平衡二叉树.md +++ b/problems/0110.平衡二叉树.md @@ -670,26 +670,35 @@ bool isBalanced(struct TreeNode* root) { ```c //计算结点深度 int getDepth(struct TreeNode* node) { + //开辟栈空间 struct TreeNode** stack = (struct TreeNode**)malloc(sizeof(struct TreeNode*) * 10000); int stackTop = 0; + //若传入结点存在,将其入栈。若不存在,函数直接返回0 if(node) stack[stackTop++] = node; int result = 0; int depth = 0; + //当栈中有元素时,进行迭代遍历 while(stackTop) { + //取出栈顶元素 struct TreeNode* tempNode = stack[--stackTop]; + //若栈顶元素非NULL,则将深度+1 if(tempNode) { depth++; + //将栈顶元素再次入栈,添加NULL表示此结点已被遍历 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 { + //若为NULL,则代表当前结点已被遍历,深度-1 tempNode = stack[--stackTop]; depth--; }