From ea6dcc9d8f5962e13bdd9f8034f244bfec450c42 Mon Sep 17 00:00:00 2001 From: Baturu <45113401+z80160280@users.noreply.github.com> Date: Sat, 5 Jun 2021 17:33:44 -0700 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 --- .../0222.完全二叉树的节点个数.md | 65 +++++++++++++++++++ 1 file changed, 65 insertions(+) diff --git a/problems/0222.完全二叉树的节点个数.md b/problems/0222.完全二叉树的节点个数.md index 2e2fed99..91e24247 100644 --- a/problems/0222.完全二叉树的节点个数.md +++ b/problems/0222.完全二叉树的节点个数.md @@ -240,6 +240,71 @@ class Solution { Python: +> 递归法: +```python +class Solution: + def countNodes(self, root: TreeNode) -> int: + return self.getNodesNum(root) + + def getNodesNum(self, cur): + if not cur: + return 0 + leftNum = self.getNodesNum(cur.left) #左 + rightNum = self.getNodesNum(cur.right) #右 + treeNum = leftNum + rightNum + 1 #中 + return treeNum +``` + +> 递归法:精简版 +```python +class Solution: + def countNodes(self, root: TreeNode) -> int: + if not root: + return 0 + return 1 + self.countNodes(root.left) + self.countNodes(root.right) +``` + +> 迭代法: +```python +import collections +class Solution: + def countNodes(self, root: TreeNode) -> int: + queue = collections.deque() + if root: + queue.append(root) + result = 0 + while queue: + size = len(queue) + for i in range(size): + node = queue.popleft() + result += 1 #记录节点数量 + if node.left: + queue.append(node.left) + if node.right: + queue.append(node.right) + return result +``` + +> 完全二叉树 +```python +class Solution: + def countNodes(self, root: TreeNode) -> int: + if not root: + return 0 + left = root.left + right = root.right + leftHeight = 0 #这里初始为0是有目的的,为了下面求指数方便 + rightHeight = 0 + while left: #求左子树深度 + left = left.left + leftHeight += 1 + while right: #求右子树深度 + right = right.right + rightHeight += 1 + if leftHeight == rightHeight: + return (2 << leftHeight) - 1 #注意(2<<1) 相当于2^2,所以leftHeight初始为0 + return self.countNodes(root.left) + self.countNodes(root.right) + 1 +``` Go: