mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-09 03:34:02 +08:00
添加 0110.平衡二叉树.md C语言迭代法注释
This commit is contained in:
@ -670,26 +670,35 @@ bool isBalanced(struct TreeNode* root) {
|
|||||||
```c
|
```c
|
||||||
//计算结点深度
|
//计算结点深度
|
||||||
int getDepth(struct TreeNode* node) {
|
int getDepth(struct TreeNode* node) {
|
||||||
|
//开辟栈空间
|
||||||
struct TreeNode** stack = (struct TreeNode**)malloc(sizeof(struct TreeNode*) * 10000);
|
struct TreeNode** stack = (struct TreeNode**)malloc(sizeof(struct TreeNode*) * 10000);
|
||||||
int stackTop = 0;
|
int stackTop = 0;
|
||||||
|
//若传入结点存在,将其入栈。若不存在,函数直接返回0
|
||||||
if(node)
|
if(node)
|
||||||
stack[stackTop++] = node;
|
stack[stackTop++] = node;
|
||||||
int result = 0;
|
int result = 0;
|
||||||
int depth = 0;
|
int depth = 0;
|
||||||
|
|
||||||
|
//当栈中有元素时,进行迭代遍历
|
||||||
while(stackTop) {
|
while(stackTop) {
|
||||||
|
//取出栈顶元素
|
||||||
struct TreeNode* tempNode = stack[--stackTop];
|
struct TreeNode* tempNode = stack[--stackTop];
|
||||||
|
//若栈顶元素非NULL,则将深度+1
|
||||||
if(tempNode) {
|
if(tempNode) {
|
||||||
depth++;
|
depth++;
|
||||||
|
//将栈顶元素再次入栈,添加NULL表示此结点已被遍历
|
||||||
stack[stackTop++] = tempNode;
|
stack[stackTop++] = tempNode;
|
||||||
stack[stackTop++] = NULL;
|
stack[stackTop++] = NULL;
|
||||||
|
//若栈顶元素有左右孩子,则将孩子结点入栈
|
||||||
if(tempNode->left)
|
if(tempNode->left)
|
||||||
stack[stackTop++] = tempNode->left;
|
stack[stackTop++] = tempNode->left;
|
||||||
if(tempNode->right)
|
if(tempNode->right)
|
||||||
stack[stackTop++] = tempNode->right;
|
stack[stackTop++] = tempNode->right;
|
||||||
|
//更新结果
|
||||||
result = result > depth ? result : depth;
|
result = result > depth ? result : depth;
|
||||||
}
|
}
|
||||||
else {
|
else {
|
||||||
|
//若为NULL,则代表当前结点已被遍历,深度-1
|
||||||
tempNode = stack[--stackTop];
|
tempNode = stack[--stackTop];
|
||||||
depth--;
|
depth--;
|
||||||
}
|
}
|
||||||
|
Reference in New Issue
Block a user