From 9a4086cd3628b0199e7e4b51eefe7dfab35688b3 Mon Sep 17 00:00:00 2001 From: ZerenZhang2022 <118794589+ZerenZhang2022@users.noreply.github.com> Date: Thu, 16 Mar 2023 19:55:49 -0400 Subject: [PATCH] =?UTF-8?q?Update=200222.=E5=AE=8C=E5=85=A8=E4=BA=8C?= =?UTF-8?q?=E5=8F=89=E6=A0=91=E7=9A=84=E8=8A=82=E7=82=B9=E4=B8=AA=E6=95=B0?= =?UTF-8?q?.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 增加完全二叉树写法2,更易理解且减少非完全二叉树节点的迭代次数 --- problems/0222.完全二叉树的节点个数.md | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/problems/0222.完全二叉树的节点个数.md b/problems/0222.完全二叉树的节点个数.md index c346b6ff..d89a9bce 100644 --- a/problems/0222.完全二叉树的节点个数.md +++ b/problems/0222.完全二叉树的节点个数.md @@ -379,6 +379,20 @@ class Solution: return (2 << leftDepth) - 1 #注意(2<<1) 相当于2^2,所以leftDepth初始为0 return self.countNodes(root.left) + self.countNodes(root.right) + 1 ``` +完全二叉树写法2 +```python +class Solution: # 利用完全二叉树特性 + def countNodes(self, root: TreeNode) -> int: + if not root: return 0 + count = 1 + left = root.left; right = root.right + while left and right: + count+=1 + left = left.left; right = right.right + if not left and not right: # 如果同时到底说明是满二叉树,反之则不是 + return 2**count-1 + return 1+self.countNodes(root.left)+self.countNodes(root.right) +``` ## Go