From f856bcfef005fc54d2e55d3e811731ce0f35257b Mon Sep 17 00:00:00 2001 From: Joshua <47053655+Joshua-Lu@users.noreply.github.com> Date: Fri, 14 May 2021 01:02:55 +0800 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.完全二叉树的节点个数 Java版本,2种解法 --- .../0222.完全二叉树的节点个数.md | 42 +++++++++++++++++++ 1 file changed, 42 insertions(+) diff --git a/problems/0222.完全二叉树的节点个数.md b/problems/0222.完全二叉树的节点个数.md index 367fa717..64705ed6 100644 --- a/problems/0222.完全二叉树的节点个数.md +++ b/problems/0222.完全二叉树的节点个数.md @@ -194,7 +194,49 @@ public: Java: +```java +class Solution { + // 通用递归解法 + public int countNodes(TreeNode root) { + if(root == null) { + return 0; + } + return countNodes(root.left) + countNodes(root.right) + 1; + } +} +``` +```java +class Solution { + /** + * 针对完全二叉树的解法 + * + * 满二叉树的结点数为:2^depth - 1 + */ + public int countNodes(TreeNode root) { + if(root == null) { + return 0; + } + int leftDepth = getDepth(root.left); + int rightDepth = getDepth(root.right); + if (leftDepth == rightDepth) {// 左子树是满二叉树 + // 2^leftDepth其实是 (2^leftDepth - 1) + 1 ,左子树 + 根结点 + return (1 << leftDepth) + countNodes(root.right); + } else {// 右子树是满二叉树 + return (1 << rightDepth) + countNodes(root.left); + } + } + + private int getDepth(TreeNode root) { + int depth = 0; + while (root != null) { + root = root.left; + depth++; + } + return depth; + } +} +``` Python: