From f3b140591b67b524e322a0dc31e3043488ea422b Mon Sep 17 00:00:00 2001 From: Arthur Date: Mon, 8 Nov 2021 14:07:24 +0000 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=200222.=E5=AE=8C=E5=85=A8?= =?UTF-8?q?=E4=BA=8C=E5=8F=89=E6=A0=91=E7=9A=84=E7=BB=93=E7=82=B9=E4=B8=AA?= =?UTF-8?q?=E6=95=B0.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../0222.完全二叉树的节点个数.md | 29 +++++++++++++++++++ 1 file changed, 29 insertions(+) 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)