添加 0110.平衡二叉树.md C语言迭代法

This commit is contained in:
Arthur
2021-11-04 10:56:41 +00:00
parent ad19a88ecf
commit 18ba708849

View File

@ -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)