添加 0222.完全二叉树的结点个数.md

This commit is contained in:
Arthur
2021-11-08 14:07:24 +00:00
parent 61044a1f94
commit f3b140591b

View File

@ -495,6 +495,35 @@ int countNodes(struct TreeNode* root){
}
```
满二叉树
```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;
}
```
-----------------------
* 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw)
* B站视频[代码随想录](https://space.bilibili.com/525438321)