Merge pull request #901 from KingArthur0205/remote

添加 0654.最大二叉树.md C语言版本, 0222.完全二叉树的结点个数.md C语言版本, 添加 0104.二叉树的最大深度.md C语言版本, 以及 添加 1047.删除字符串中的所有相邻重复项.md C语言版本
This commit is contained in:
程序员Carl
2021-11-17 15:53:42 +08:00
committed by GitHub
5 changed files with 210 additions and 1 deletions

View File

@@ -446,7 +446,80 @@ var countNodes = function(root) {
};
```
## C:
递归法
```c
int countNodes(struct TreeNode* root) {
//若传入结点不存在返回0
if(!root)
return 0;
//算出左右子树的结点总数
int leftCount = countNodes(root->left);
int rightCount = countNodes(root->right);
//返回左右子树结点总数+1
return leftCount + rightCount + 1;
}
int countNodes(struct TreeNode* root){
return getNodes(root);
}
```
迭代法
```c
int countNodes(struct TreeNode* root){
//记录结点总数
int totalNum = 0;
//开辟栈空间
struct TreeNode** stack = (struct TreeNode**)malloc(sizeof(struct TreeNode*) * 100);
int stackTop = 0;
//如果root结点不为NULL则将其入栈。若为NULL则不会进入遍历返回0
if(root)
stack[stackTop++] = root;
//若栈中有结点存在,则进行遍历
while(stackTop) {
//取出栈顶元素
struct TreeNode* tempNode = stack[--stackTop];
//结点总数+1
totalNum++;
//若栈顶结点有左右孩子,将它们入栈
if(tempNode->left)
stack[stackTop++] = tempNode->left;
if(tempNode->right)
stack[stackTop++] = tempNode->right;
}
return totalNum;
}
```
满二叉树
```c
int countNodes(struct TreeNode* root){
if(!root)
return 0;
int leftHeight = 0;
int rightHeight = 0;
struct TreeNode* rightNode = root->right;
struct TreeNode* leftNode = root->left;
//求出左子树深度
while(leftNode) {
leftNode = leftNode->left;
leftHeight++;
}
//求出右子树深度
while(rightNode) {
rightNode = rightNode->right;
rightHeight++;
}
//若左右子树深度相同为满二叉树。结点个数为2^height-1
if(rightHeight == leftHeight) {
return (2 << leftHeight) - 1;
}
//否则返回左右子树的结点个数+1
return countNodes(root->right) + countNodes(root->left) + 1;
}
```
-----------------------
<p align="center">