mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-09 03:34:02 +08:00
添加 0222.完全二叉树的节点个数.md C语言迭代法、递归法
This commit is contained in:
@ -449,7 +449,51 @@ 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;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
-----------------------
|
-----------------------
|
||||||
* 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw)
|
* 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw)
|
||||||
|
Reference in New Issue
Block a user