mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 08:50:15 +08:00
添加 0110.平衡二叉树.md C语言迭代法注释
This commit is contained in:
@ -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--;
|
||||
}
|
||||
|
Reference in New Issue
Block a user