diff --git a/problems/0222.完全二叉树的节点个数.md b/problems/0222.完全二叉树的节点个数.md index 0826110f..14e1537a 100644 --- a/problems/0222.完全二叉树的节点个数.md +++ b/problems/0222.完全二叉树的节点个数.md @@ -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)