mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 16:54:50 +08:00
添加 0222.完全二叉树的结点个数.md
This commit is contained in:
@ -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)
|
||||
|
Reference in New Issue
Block a user