From d971558d3b7d4ef924eac935451d2bfdfbb6a0dd Mon Sep 17 00:00:00 2001 From: NevS <1173325467@qq.com> Date: Fri, 18 Jun 2021 22:45:20 +0800 Subject: [PATCH 1/2] =?UTF-8?q?=E5=A2=9E=E5=8A=A0=200222.=E5=AE=8C?= =?UTF-8?q?=E5=85=A8=E4=BA=8C=E5=8F=89=E6=A0=91=E7=9A=84=E8=8A=82=E7=82=B9?= =?UTF-8?q?=E4=B8=AA=E6=95=B0=20go=E7=89=88=20=EF=BC=88=E6=96=B0=E5=A2=9E?= =?UTF-8?q?=E5=88=A9=E7=94=A8=E5=AE=8C=E5=85=A8=E4=BA=8C=E5=8F=89=E6=A0=91?= =?UTF-8?q?=E7=89=B9=E6=80=A7=E7=9A=84=E9=80=92=E5=BD=92=E8=A7=A3=E6=B3=95?= =?UTF-8?q?=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 新增利用完全二叉树特性的递归解法 --- .../0222.完全二叉树的节点个数.md | 24 +++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/problems/0222.完全二叉树的节点个数.md b/problems/0222.完全二叉树的节点个数.md index 998e22f3..ec68b6c6 100644 --- a/problems/0222.完全二叉树的节点个数.md +++ b/problems/0222.完全二叉树的节点个数.md @@ -335,6 +335,30 @@ func countNodes(root *TreeNode) int { } ``` +利用完全二叉树特性的递归解法 +```go +func countNodes(root *TreeNode) int { + if root == nil { + return 0 + } + leftH, rightH := 0, 0 + leftNode := root.Left + rightNode := root.Right + for leftNode != nil { + leftNode = leftNode.Left + leftH++ + } + for rightNode != nil { + rightNode = rightNode.Right + rightH++ + } + if leftH == rightH { + return (2 << leftH) - 1 + } + return countNodes(root.Left) + countNodes(root.Right) + 1 +} +``` + JavaScript: From a85e41093b1b94a2aa63109459fdcb0647a813b2 Mon Sep 17 00:00:00 2001 From: NevS <1173325467@qq.com> Date: Sun, 20 Jun 2021 00:45:47 +0800 Subject: [PATCH 2/2] =?UTF-8?q?=E5=A2=9E=E5=8A=A0=200257.=E4=BA=8C?= =?UTF-8?q?=E5=8F=89=E6=A0=91=E7=9A=84=E6=89=80=E6=9C=89=E8=B7=AF=E5=BE=84?= =?UTF-8?q?=20go=20=E7=89=88?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0257.二叉树的所有路径.md | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/problems/0257.二叉树的所有路径.md b/problems/0257.二叉树的所有路径.md index fe7a2604..d5a0478e 100644 --- a/problems/0257.二叉树的所有路径.md +++ b/problems/0257.二叉树的所有路径.md @@ -350,6 +350,29 @@ class Solution: ``` Go: + +```go +func binaryTreePaths(root *TreeNode) []string { + res := make([]string, 0) + var travel func(node *TreeNode, s string) + travel = func(node *TreeNode, s string) { + if node.Left == nil && node.Right == nil { + v := s + strconv.Itoa(node.Val) + res = append(res, v) + return + } + s = s + strconv.Itoa(node.Val) + "->" + if node.Left != nil { + travel(node.Left, s) + } + if node.Right != nil { + travel(node.Right, s) + } + } + travel(root, "") + return res +} +``` JavaScript: 1.递归版本